【Python学习】之yagmail库实现发送邮件
上代码:
import yagmail sendmail = 'xxx@126.com' sendpswd = 'xxx' receivemail = 'xxx@qq.com' # 连接邮箱服务器 yag = yagmail.SMTP(user=sendmail, password=sendpswd, host='smtp.126.com') # ①普通邮件正文 contents = ['第一段', '自动化', '报告邮件'] # ②发送html邮件正文 # 读取邮件模板 file_object = open('mailcontent.html') try: contentsbody = file_object.read() finally: file_object.close() contents = contentsbody # 附件地址 fujian = ["/Users/zhan/zhan/Autotest/report/2018-09-11_09_52_24_report.html"] # 发送邮件附件 yag.send(receivemail, '《自动化报告》', contents,fujian)
参考:《利用yagmail实现邮件自动发送》
老的发送邮箱写法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from smtplib import SMTP from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from email.header import Header from email.mime.text import MIMEText def getNewReport(report_url): ''' 获取最新生成的测试报告 :param report_url: :return: ''' lists = os.listdir(report_url) lists.sort(key= lambda fn: os.path.getmtime(report_url + fn)) newReport = os.path.join(report_url,lists[-1]) return newReport def sendMail(newReport,report_name): ''' ①普通发送邮件 :param newReport: :param report_name: :return: ''' sendMail = 'xxx@126.com' sendpswd = 'xxx' receiveMail = 'xxx@qq.com' # 创建邮件信息 msg = MIMEMultipart() # 读取最新报告文件 f = open(newReport,'rb').read() # 设置邮件主体 mailBody = MIMEText(f,'html','utf-8') # 邮件主体放入到消息中 msg.attach(mailBody) # 邮件标题 msg['Subject'] = Header("《自动化测试报告邮件》",'utf-8') msg['From'] = sendMail msg['To'] = receiveMail # 邮件附件 att = MIMEApplication(f) att['Content-Type'] = 'application/octet-stream' att.add_header('Content-Disposition','attachment',filename=report_name) msg.attach(att) smtp = SMTP() # 连接邮箱 smtp.connect('smtp.126.com') # 邮箱登录 smtp.login(sendMail,sendpswd) # 发送邮件 smtp.sendmail(sendMail,receiveMail,msg.as_string())
不积跬步,无以致千里;不集小流,无以成江海。
如转载本文,请还多关注一下我的博客:https://www.cnblogs.com/Owen-ET/;
我的Github地址:https://github.com/Owen-ET————————————
无善无恶心之体, 有善有恶意之动, 知善知恶是良知, 为善去恶是格物。