python+requests之三: 发送邮件

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') 

这行代码不规范,正确的写法应该是:

        message = MIMEMultipart()  #创建邮件实例       
        message['from']= formataddr(['发件人姓名',senderemail]) #括号里对应发件人邮箱昵称
        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 + "path.txt"
        att1 = MIMEApplication(open(file,'r').read())
        att1["Content-Disposition"] = 'attachment;filename="abc.txt"'
        message.attach(att1)

 上述代码运行结果:

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)

猜你喜欢

转载自blog.csdn.net/wdlnancy/article/details/87604808