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

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

   
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)

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值