yagmail模块是python中用来发送邮件的第三方模块,简单快速。
环境
- python3.9
- win10 64bit
- yagmail==0.14.245
快速了解
下面是一份代码样本,用来可以快速了解一下yagmail模块的使用。
import yagmail
try:
yag=yagmail.SMTP(user='11111@qq.com',password='authorization code',host='smtp.qq.com')
yag.send(to='22222@qq.com',subject='test',contents='Hello')
print('Email send success')
except:
print('Email send fail')
Email send success
先导入了yagmail模块,通过SMTP创建了smtp服务实例yag,在利用实例的send方法发送邮件。
在创建smtp服务实例的时候,需要注意几点:
-
user:发件人邮箱地址 -
password:发件人邮箱是smtp服务的授权码(并非登录密码) -
host:发件人邮箱的smtp服务器地址
上文是以qq邮箱为例,其他邮箱类似,都需要获取授权码。
send方法用来发送邮件,主要设置的参数有:
-
to: 收件人邮箱地址 -
subject: 邮件主题 -
contents: 邮件内容
多个收件人
设置to参数为list类型,可以给多个人发邮件。
yag.send(to=['22222@qq.com','33333@qq.com'],subject='test',contents='Hello')
添加抄送
设置send方法中的cc(抄送)和bcc(秘密抄送)参数,可添加抄送。当需要抄送或秘密抄送多个人时,cc/bcc参数设置为list。
# 添加抄送和秘密抄送
yag.send(to='22222@qq.com',subject='test',contents='Hello',cc='33333@qq.com',bcc='44444@qq.com')
# 添加多个抄送和秘密抄送
yag.send(to='22222@qq.com',subject='test',contents='Hello',
cc=['33333@qq.com','44444@qq.com'],bcc=['55555@qq.com','66666@qq.com'])
添加附件
设置send方法中的attachments参数,可添加附件。需要添加多个附件时,attachments参数设置为list。
# 添加单个附件
yag.send(to='22222@qq.com',subject='test',contents='Hello',attachments=r'E:\blog\python-email\email.jpg')
Email send fail
# 添加多个附件
yag.send(to='22222@qq.com',subject='test',contents='Hello',
attachments=[r'E:\blog\python-email\email.jpg',r'E:\blog\python-email\auto.jpg'])
发送HTML内容
send方法中的contents参数为邮件的内容,可以设置为html字符。
# 发送html内容
yag.send(to='22222@qq.com',subject='test',contents='<h1>Hello</h1>')