#自定义处理邮件收发地址的显示内容
def _format_addr(s):
name,addr = parseaddr(s)
print name
print addr
#将邮件的name转换成utf-8格式,addr如果是unicode,则转换utf-8输出,否则直接输出addr
return formataddr((\
Header(name,'utf-8').encode(),\
def _format_addr(s):
name,addr = parseaddr(s)
print name
print addr
#将邮件的name转换成utf-8格式,addr如果是unicode,则转换utf-8输出,否则直接输出addr
return formataddr((\
Header(name,'utf-8').encode(),\
addr.encode("utf-8") if isinstance(addr,unicode) else addr))
#邮件对象
msg['From'] = _format_addr(u'测试机 <%s>'%from_addr)
msg['to'] = _format_addr(u'吴鹏rhythm <%s>'%to_addr)
下图是使用上面代码后,收发件人的邮箱地址显示
以下是python自动发送邮件的完整代码:
#coding=utf-8
from email.header import Header
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.utils import parseaddr,formataddr
import smtplib,time,os
def filepath(): filepath = "D:\\Python27\\selenium_\\report"listdirs = os.listdir(filepath)listdir = sorted(listdirs)filename = os.path.join(filepath,listdir[-1])return filenamedef sendmail(reportfile):from_addr = "wupeng@formssi.com"password = "xxxxxx"to_addr = "qq32712784@163.com"smtp_server = "smtp.formssi.com"#自定义处理邮件收发地址的显示内容def _format_addr(s):name,addr = parseaddr(s)print nameprint addr#将邮件的name转换成utf-8格式,addr如果是unicode,则转换utf-8输出,否则直接输出addrreturn formataddr((\Header(name,'utf-8').encode(),\addr.encode("utf-8") if isinstance(addr,unicode) else addr))#读取html内容filepath = reportfilewith open(filepath,'rb') as f:content = f.read()#邮件正文是MIMETextmsg = MIMEText(content,'html','utf-8')#邮件对象msg['From'] = _format_addr(u'测试机 <%s>'%from_addr)msg['to'] = _format_addr(u'吴鹏rhythm <%s>'%to_addr)msg['Subject'] = Header(u'测试报告自动发送','utf-8').encode()msg['date'] = time.strftime("%a,%d %b %Y %H:%M:%S %z")#发送邮件server = smtplib.SMTP(smtp_server,25)server.set_debuglevel(1)server.login(from_addr,password)server.sendmail(from_addr,to_addr,msg.as_string())server.quit()if __name__ == "__main__":filedir = filepath()sendmail(filedir)