1、发送邮件message[to] message[subject]代码在代码
MIMEText(content,'html','utf-8')之后,邮件里可正常看到主题及收件人
2、但若message[to]和message[subject]在上述代码之前,则发送的邮件里看不到主题和收件人:
3、即使按照步骤1的方式编写,但下面若添加附件时,仍然抛异常:MultipartConversionError('Cannot attach additional subparts to non-multipart/*',),其实是因为
message = MIMEText(content,'html','utf-8')
这行代码不规范,正确的写法应该是:
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from testStub.framework.email_config import GetConfigEmail
from email.mime.application import MIMEApplication
email_config = GetConfigEmail()
sender,password,senderemail =email_config.get_senderinfo() # 发件人邮箱
addressed_emails = email_config.get_receivers() #收件人邮箱
import os
class Mail(object):
def __init__(self):
try:
message = MIMEMultipart()
message['from']= formataddr(['发件人姓名',senderemail]) #括号里对应发件人邮箱昵称
print ("formataddr[发件人姓名]")
print (message['from'])
message['Subject']="xxx接口自动化测试报告"
message['to'] = formataddr(['收件人邮箱',",".join(addressed_emails)])
#添加邮件正文
content = '<h1>123456789</h1><br/><h2>This line change!这里换行!</h2>'
text = MIMEText(content,'html','utf-8')
message.attach(text)
#邮件附件
report_path = os.path.dirname(os.path.abspath("."))+"\\test_report\\"
#file = report_path + "2019-02-11-14-21-00HTMLtemplate.html"
file = report_path + "test.txt"
att1 = MIMEText(open(file,'rb').read(),'base64','utf-8')
att1["Content-Type"]='application/octet-stream'
#att1["Content-Disposition"] = 'attachment;filename="abc.html"'
att1["Content-Disposition"] = 'attachment;filename="abc.txt"'
message.attach(att1)
client = smtplib
client = smtplib.SMTP()
client.connect("smtp.huawei.com","25")
client.login(sender,password)
client.sendmail(senderemail,["wudanlu@huawei.com","wudanlu@huawei.com"],message.as_string())
except Exception as e:
print("邮件发送失败"+repr(e))
finally:
client.quit()
if __name__ == '__main__':
Mail()
上述代码运行结果:
4、发送html格式的附件:
report_path = os.path.dirname(os.path.abspath("."))+"\\test_report\\"
file = report_path + "2019-02-14-16-55-49HTMLtemplate.html"
att1 = MIMEText(open(file,'rb').read(),'base64','utf-8')
att1["Content-Type"]='application/octet-stream'
att1["Content-Disposition"] = 'attachment;filename="abc.html"'
message.attach(att1)