python3发送邮件

自动化测试用例上百条的时间运行时间较长,这时可以悠闲的干点别的事情,然后你也不知道什么时候会结束,但既然时自动化那必须会发邮件通知,所有我们来学习一下利用python发送邮件,后续在添加测试报告在里面。

废话不多说,上代码

1 import smtplib 2 from email.mime.text import MIMEText 3 from email.header import Header 4 5 #发生邮箱服务器 6 smtpserver = 'smtp.qq.com' 7 #发送用户和密码 8 user = 'name@qq.com' 9 password = '**********' 10 #发送邮箱 11 sender = 'name@qq.com' 12 #接收邮箱 13 receiver = '******@qq.com' 14 #发送邮箱主题 15 subject = 'python test' 16 #编写HTML类型的邮件正文 17 msg = MIMEText('<html><h1>你好!我是python测试邮件!</h1><html>','html','utf-8') 18 msg['Subject'] = Header(subject,'utf-8') 19 #连接发送邮件 20 smtp = smtplib.SMTP() 21 smtp.connect(smtpserver) 22 smtp.login(user,password) 23 smtp.sendmail(sender,receiver,msg.as_string()) 24 smtp.quit()

注意:password不要填你的密码,要填你邮箱生成的授权码。如下图点击生成授权码同时必须要开启SMTP服务哦,另外还有一个地方需要注意发送的邮箱服务器如果是qq就按我上面的填,新浪的话改成

'smtp.sina.com'其他的邮箱就改中间的标签好了。

 不然会出现如下错误

 

 经过上面的步骤终于成功发出了邮件,上图。

以上只是发送文字,那么要发送附件呢?经过又一番修改,终于也成功了。代码如下

1 import smtplib 2 from email.mime.text import MIMEText 3 from email.mime.multipart import MIMEMultipart 4 5 #发生邮箱服务器 6 smtpserver = 'smtp.qq.com' 7 #发送用户和密码 8 user = 'name@qq.com' 9 password = '************' 10 #发送邮箱 11 sender = 'name@qq.com' 12 #接收邮箱 13 receiver = 'her_name@qq.com' 14 #发送邮箱主题 15 subject = 'python test' 16 #发送附件 17 sendfile = open('F:\\cs.txt','rb').read() 18 19 att = MIMEText(sendfile,'base64','utf-8') 20 att["Content-Type"] = 'application/octet-stream' 21 att["Content-Disposition"] = 'attachment; filename="cs.txt"' 22 23 msgRoot = MIMEMultipart('related') 24 msgRoot['Subject'] = subject 25 msgRoot.attach(att) 26 27 #编写HTML类型的邮件正文 28 # msg = MIMEText('<html><h1>你好!我是python测试邮件!</h1><html>','html','utf-8') 29 # msg['Subject'] = Header(subject,'utf-8') 30 # #连接发送邮件 31 smtp = smtplib.SMTP() 32 smtp.connect(smtpserver) 33 smtp.login(user,password) 34 smtp.sendmail(sender,receiver,msgRoot.as_string()) 35 smtp.quit()

__EOF__

本文作者Harry
本文链接https://www.cnblogs.com/harry66/p/12081330.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   Harry_666  阅读(794)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示