一.yagmail基本数据准备
1.终端下载yagmail:pip install yagmail
2.获取SMTP和密钥
我们以新浪邮箱为例,登录成功后进入设置页面,点击客户端pop/imap/smtp分类栏,会看见IMAP4服务/SMTP服务
SMTP就是客户端设置下SMTP服务器的值,密钥的话在你开启服务状态成功后会弹出(如果原本就是开启状态,需先
关闭后再开启)。
二.发送正文
1.与邮箱服务器建立连接
python;gutter:true;
smtps = yagmail.SMTP(user='your@sina.com', password='密钥', host='SMTP服务器') # 建立连接</p>
<pre><code>
user:你的邮箱地址
password:密钥值,不是邮箱密码
host:SMTP值
2.通过send()方法发送邮件
;gutter:true;
smtps.send(to="123456@qq.com", subject="标题", contents="正文")
to:指定接收人的邮箱
subject:邮件标题
contents:邮件正文内容
3.contents属性
1)可直接输入发送的内容或图片以及文件地址,会自动识别传递的内容格式,若是图片/文件会以附件的方式发送给目标邮箱
2)可将内容格式编辑在文件中,直接读取文件内容发送
python;gutter:true;
with open("./txt/yag.txt", mode="r", encoding="utf-8")as a:
data = a.read()
smtps.send(to="123456@qq.com", subject="标题", contents=data)</p>
<pre><code>
4.关闭连接
;gutter:true;
smtps.close()
三.发送附件
1.发送单个附件
python;gutter:true;
smtps.send(to="123456@qq.com", subject="标题", contents="正文",attachments="文件地址")</p>
<pre><code>
attachments:附件
2.发送多个附件
;gutter:true;
att_list = [‘./img/base64.png’, ‘yag.txt’]
smtps.send(to="123456@qq.com", subject="标题", contents="正文", attachments=att_list)
attachments:可传list
四.收件人起别名
python;gutter:true;
reci = {
'123456@QQ.com': "qq" # 取别名
}
smtps.send(to=reci, subject="标题", contents="正文")</p>
<pre><code>
若发送多个邮箱都起别名的话,可在reci中添加多个
### 五.多人发送
;gutter:true;
to_list = [‘123456@qq.com’, ‘123456@163.com’]
smtps.send(to=to_list, subject="标题", contents="正文")
to:可传递list
六.多人抄送和密抄
python;gutter:true;
cc_list = ['123456@qq.com', '123456@163.com']
bcc_list = ['123456@sina.com']
smtps.send(to="123456@qq.com", subject="标题", contents="正文",cc=cc_list,bcc=bcc_list)</p>
<pre><code>
cc:抄送
bcc:密抄
### 七.发送html测试报告
1.生成html文件:pytest --html=生成报告的url --self-contained-html 运行用例的.py文件
2.以附件的形式发送
;gutter:true;
smtps.send(to="123456@qq.com", subject="发送自动化测试报告html", contents="html", attachments="html地址")
文章来源:https://www.cnblogs.com/lihongtaoya/ ,请不要转载
Original: https://www.cnblogs.com/lihongtaoya/p/16725231.html
Author: 傻姑娘家的李先生
Title: 使用yagmail发送邮件
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/602220/
转载文章受原作者版权保护。转载请注明原作者出处!