依赖的安装
pip install yagmail
给单个接受者发送邮箱,对比email、smtp模块,yagmail的实现真的是太简单了,感动的要哭了~~~~
import yagmail
#链接邮箱服务器
yag = yagmail.SMTP(user="sender@126.com", password="126邮箱授权码", host='smtp.126.com')
#邮箱正文
contents = ['This is the body, and here is just text http://somedomain/image.png',
'You can find an audio file attached.', '/local/path/song.mp3']
# 发送邮件
yag.send(receiver@qq.com', 'subject', contents)
给多个接受者发送邮件
# 发送邮件
yag.send(['aa@126.com','bb@qq.com','cc@gmail.com'], 'subject', contents)
发送带附件的邮件
yag.send('aaaa@126.com', '发送附件', contents, ["E://whitelist.txt","E://baidu_img.jpg"])
实际操作
import yagmail
#链接邮箱服务器
yag = yagmail.SMTP( user="user@126.com", password="1234", host='smtp.126.com')
# 邮箱正文
contents = ['This is the body, and here is just text http://somedomain/image.png',
'You can find an audio file attached.', '/local/path/song.mp3']
# 发送邮件
mail.send(
to=['123@qq.com','1255@qq.com'], #如果多个收件人的话,写成list就行了,如果只是一个账号,就直接写字符串就行to='123@qq.com'
cc='735@qq.com',#抄送
subject='学习发送邮件',#邮件标题
contents='你好,你今天开心吗?',#邮件正文
attachments=[r'd://log.txt', r'd://baidu_img.jpg'])#附件如果只有一个的话,用字符串就行,attachments=r'd://baidu_img.jpg'
可简写成:
yag.send('aaaa@126.com', '发送附件', contents, ["d://log.txt","d://baidu_img.jpg"])
#关闭yag.close()
或者写个函数
import yagmail
def send_mail(content,send_to="280898098@qq.com"):
yag=yagmail.SMTP(user="youemail@sohu.com",password="xxxx",
host="smtp.sohu.com",port='465')
yag.send(to=send_to,
subject="天气关怀",
contents=content)
print('发送成功!')