開發語言: python2.7 包:smtplib
導入包:
import smtplib
定義一個函數:
def send_mail(to_list, cc_list, html, sub): me = mail_user msg = MIMEText(html, _subtype='html', _charset='utf-8') # 格式化郵件內容爲html,編碼爲utf-8 msg['Subject'] = sub # 郵件主題 msg['From'] = me # 發件人 msg['To'] = ";".join(to_list) # 收件人,將列表轉換爲字符串 msg['Cc'] = ";".join(cc_list) # 抄送人,將列表轉換爲字符串 try: send_smtp = smtplib.SMTP() # 實例化 send_smtp.connect(mail_host) # 連接smtp服務器 send_smtp.login(mail_user, mail_pass) # 使用定義的賬號密碼進行登錄 send_smtp.sendmail(me, to_list+cc_list, msg.as_string()) # 發送郵件 send_smtp.close() # 關閉連接 return True except Exception, e: # logging.debug(e) print e return False
其中:“to_list”爲收件人列表(可以爲一個或者多個),“cc_list”爲抄送列表(同樣爲一個或多個),“html”爲郵件內容,可以發送html格式的郵件,“sub”爲郵件主題。
調用發送郵件函數:
if __name__ == '__main__': mail_host = '[email protected]' mail_user = '[email protected]' mail_pass = 'password' mailto_list = ['[email protected]', '[email protected]', '[email protected]'] mailcc_list = ['[email protected]'] html = "<h1> test page</h1>" sub = "send mail test" if send_mail(mailto_list, mailcc_list, strhtml, sub): logging.debug("Send mail succed!") else: logging.debug("Send mail failed")
在搜索資料過程中,發現很多人說抄送功能無法實現,可能是因爲列表和字符串之間的轉換問題,或者是由於send_smtp.sendmail()函數的格式問題,雖然沒有報錯,但是沒有發送成功。
建議大家在使用時,如果沒有發送成功或者是抄送成功,可以在
to_list,cc_list,msg['To'],msg['Cc']
這裏加上print,看一下類型和是否正確;
附smtplib源碼地址:
https://hg.python.org/cpython/file/2.7/Lib/smtplib.py