2012-08-22 47 views
-1

使用SMTP我有一個問題郵件上我將如何使用這個發送在python

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) 

這裏是我的代碼:

import sys 
    import os 
    import re 
    from smtplib import SMTP_SSL as SMTP 
    from email.MIMEMultipart import MIMEMultipart 
    from email.MIMEText import MIMEText 

    SMTPserver = 'server.me.com' 
    sender =  '[email protected]' 
    destination = '[email protected]' 
    recipient = ['[email protected]', '[email protected]', '[email protected]'] 

    USERNAME = 'user' 
    PASSWORD = 'pass' 
    text_subtype = 'plain' 
    content='This is a test for mail sending' 
    subject='Test' 

    try: 
     msg = MIMEMultipart() 
     msg = MIMEText(content, text_subtype) 
     msg['From'] = sender 
     msg['To'] = destination 
     msg['Cc'] = ', '.join(recipient) 
     msg['Subject']= subject 

     conn = SMTP(SMTPserver) 
     conn.login(USERNAME, PASSWORD) 
     try: 
      **conn.sendmail(sender, destination, msg.as_string())** 
     except Exception, exc: 
      sys.exit("connection failed; %s" % str(exc)) 
     finally: 
      conn.close() 

    except Exception, exc: 
     sys.exit("mail failed; %s" % str(exc)) 

這是一個正確的語法或代碼?我想要的是我也想將郵件發送到收件人列表,但我應該在哪裏放入代碼?

+1

請比'我有問題'更具體。你有什麼問題?你能告訴我們你得到了什麼錯誤嗎? –

回答

1

這幾乎可以。你有沒有嘗試過使用你的代碼(另見評論)? 你需要注意的唯一的事情是conn.sendmail()中的destination需要是一個列表,所以[destination]。然後,您可以很容易地用recipient替換它,因爲這已經是一個列表。 這裏有一些很好的例子:http://docs.python.org/library/email-examples.html#email-examples,你的代碼幾乎和那些例子中的一樣。

當您運行代碼並得到一個無法解決的實際錯誤時,歡迎您回到這裏並提出一個新問題。