下面提供了一個使用python做的發送文本內容的郵件代碼,能夠在郵件內容中設置文字顏色,大小,換行等功能。
#auther by zls #_*_coding:utf-8_*_ import sys reload(sys) sys.setdefaultencoding('utf8') #####上面這個導入是為了解決傳入utf8類型的內容時造成UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe5 in position 108: ordinal not in range(128)這個錯誤,詳情見這個文章http://blog.csdn.net/mindmb/article/details/7898528 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage HOST = "smtp.XXX.com" SUBJECT = u"zabbix每日報表" TO = [ "xxx@xxx.com", "xxx2@xxx.com" ] FROM = "xxx.xxx.com" line1 = "這是第一行" #郵件正文第一行內容 line2 = "這是第二行" #郵件正文第二行內容 line3 = "這是第三行" #郵件正文第三方內容 msg = MIMEMultipart('related') msgtext = MIMEText("<font color=red>zabbix每日報表:<br>第一行:%s<br>第二行:%s<br>第三行:%s<br>詳細內容見附件。</font>" %(line1, line2 ,line3), "html", "utf-8") msg.attach(msgtext) msg['Subject'] = SUBJECT msg['From'] = FROM msg['To'] = ",".join(TO) try: server = smtplib.SMTP() server.connect(HOST, "端口號") server.starttls() server.login("用於發信的用戶名", "密碼") server.sendmail(FROM, TO, msg.as_string()) server.quit() print "郵件發送成功!" except Exception, e: print "失敗:" + str(e)