1. 程式人生 > >Python傳送郵件並抄送

Python傳送郵件並抄送

轉載: http://blog.51cto.com/lizhenliang/1875330

程式碼

#!/usr/bin/python
# -*- coding: utf-8 -*-
import smtplib

def sendMail(body):
    smtp_server = 'smtp.163.com'
    from_mail = '[email protected]'
    mail_pass = 'your_email_password'
    to_mail = ['[email protected]', '[email protected]
'] cc_mail = ['[email protected]'] from_name = 'monitor' subject = u'[重要通知][CW] xxx 程式已執行到預定位置, 請及時處理!'.encode('gbk') # 以gbk編碼傳送,一般郵件客戶端都能識別 # msg = '''\ # From: %s <%s> # To: %s # Subject: %s # %s''' %(from_name, from_mail, to_mail_str, subject, body) # 這種方式必須將郵件頭資訊靠左,也就是每行開頭不能用空格,否則報SMTP 554 mail = [ "From: %s <%s>" % (from_name, from_mail), "To: %s" % ','.join(to_mail), # 轉成字串,以逗號分隔元素 "Subject: %s" % subject, "Cc: %s" % ','.join(cc_mail), "", body ] msg = '\n'.join(mail) # 這種方式先將頭資訊放到列表中,然後用join拼接,並以換行符分隔元素,結果就是和上面註釋一樣了 try: s = smtplib.SMTP() s.connect(smtp_server, '25') s.login(from_mail, mail_pass) s.sendmail(from_mail, to_mail+cc_mail, msg) s.quit() except smtplib.SMTPException as e: print "Error: %s" %e if __name__ == "__main__": sendMail("[Sending Reason] Aliyun had a list overflow event, please deal with it in time! \n\nMore Details: ......")