【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实现邮件自动发送》
老的发送邮箱写法:

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————————————
无善无恶心之体, 有善有恶意之动, 知善知恶是良知, 为善去恶是格物。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App