idning 2019-12-21
# 使用163邮箱发送邮件 # 1.先导入smtplib库用来发送邮件,导入MIMEText库用来做纯文本的邮件模板 import smtplib from email.mime.text import MIMEText # 发送带附件的需要导入另外一个模块MIMEMultipart from email.mime.multipart import MIMEMultipart------------------------------------------------------------------------------------------ # 2.定义附件路径 file_path = r‘D:\Python_Script\TetsInterface\reports\1576631030.html‘ # 打开文件 with open(file_path,‘rb‘)as fp: file_data = fp.read() # ----------------------------------准备跟发件相关参数--------------------------------------- smtp_server = ‘smtp.163.com‘ # 发件服务器 prot = 0 # 端口 sender_user = ‘‘ # 发件人账号 pwd = ‘*******‘ # 发件人密码 receivers = [‘‘,‘‘] # 需要多个收件人 # 4. --------------------------------编辑邮件内容------------------------------------------- subject = ‘这是接口自动化测试报告‘ # 邮件主题 msg = MIMEMultipart() msg[‘from‘] = sender_user # 定义发件人 msg[‘to‘] = ‘;‘.join(receivers) # 定义收件人,多个收件人不可直接接收列表,需要通过分号隔开 msg[‘subject‘] = subject # 邮件主题 body = MIMEText(file_data,‘html‘,‘utf-8‘) # 邮件正文 msg.attach(body) # ------------------------------------附件-------------------------------------------------- accessory = MIMEText(file_data,‘base64‘,‘utf-8‘) accessory["Content-Type"] = "application/octet-stream" accessory["Content-Disposition"] = ‘attachment; filename="test_report.html"‘ #附件重命名 msg.attach(accessory) # -----------------------------------准备发送------------------------------------------------ smtp = smtplib.SMTP() smtp.connect(smtp_server) smtp.login(sender_user,pwd) #登录 smtp.sendmail(sender_user,receivers,msg.as_string()) # 发送 smtp.quit() # 退出