分别是发送纯文本邮件、html格式邮件,以及带附件的html格式邮件。纯文本邮件消息体是普通字符串,html格式邮件中消息体是MIMEText型对象,这种对象的特点是不能加附件;带附件的html格式邮件中消息体是MIMEMultipart型对象,正文和附件都用attach()方法添加。
代码如下(红色字体部分是一个html格式文本的示例,可跳过不看):
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
if name=='main':
msg_body=''' <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
Unit Test Results Summary
Tests | Failures | Errors | Success rate | Time |
---|---|---|---|---|
382 | 3 | 382 | 36.0466666667% | 1.65 |
Diffcount Report
GODU SERVER
LANG | ADD | MOD | DEL | A&M | BLK | CMT | NBNC | RATE |
---|---|---|---|---|---|---|---|---|
Java | 52774 | 0 | 0 | 52774 | 5501 | 8036 | 39344 | 0.41 |
XML | 399 | 0 | 0 | 399 | 0 | 0 | 399 | 0.12 |
GAPI
LANG | ADD | MOD | DEL | A&M | BLK | CMT | NBNC | RATE |
---|---|---|---|---|---|---|---|---|
Java | 52774 | 0 | 0 | 52774 | 5501 | 8036 | 39344 | 0.41 |
XML | 399 | 0 | 0 | 399 | 0 | 0 | 399 | 0.12 |
GODU WEB
LANG | ADD | MOD | DEL | A&M | BLK | CMT | NBNC | RATE |
---|---|---|---|---|---|---|---|---|
Java | 52774 | 0 | 0 | 52774 | 5501 | 8036 | 39344 | 0.41 |
XML | 399 | 0 | 0 | 399 | 0 | 0 | 399 | 0.12 |
'''
mail_server = smtplib.SMTP('124.127.106.5') # use 'smtp.163.com' to send email with 163
mail_server.set_debuglevel(1)
mail_server.login('lichao1', 'abaqus67')
#发送纯文本邮件
#from_addr = 'LiChaolichao1@boco.com.cn'
#to_addr = 'LiChaolichao1@boco.com.cn'
#subj = 'hello'
#date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")
#msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % (from_addr, to_addr, subj, date, message_body)
#mail_server.sendmail(from_addr, to_addr, msg)
#发送html格式邮件
#msg = MIMEText (msg_body, 'html')
#msg['From'] = 'LiChaolichao1@boco.com.cn'
#msg['To'] = 'LiChaolichao1@boco.com.cn'
#msg['Subject'] = 'hello'
#mail_server.sendmail('LiChaolichao1@boco.com.cn', 'LiChaolichao1@boco.com.cn', msg.as_string())
#发送带附件的html格式邮件
msg = MIMEMultipart ()
part2 = MIMEText(msg_body, 'html')
msg. attach (part2)
att = MIMEText(open('e:\BVT\GODU-BVT\GCIF\build\2011-01-12\GAPI\build\result\junit\junit-noframes.html', 'rt').read())
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="JUnitReport.html"'
msg. attach (att)
msg['From'] = 'LiChaolichao1@boco.com.cn'
msg['To'] = 'LiChaolichao1@boco.com.cn'
msg['Subject'] = 'hello'
mail_server.sendmail('LiChaolichao1@boco.com.cn', 'LiChaolichao1@boco.com.cn', msg.as_string())
mail_server.quit()
注意:sendmail()发送邮件时,如果收件人有多个,必须放在一个list中作为参数,如果是字符串,则只发给第一个人,似乎只有python2.6要求是list型参数。