Python自动发邮件-yagmail库,怎么发邮件到gmail,之前写过用标准库使用


之前写过用标准库使用Python Smtplib和email发送邮件,感觉很繁琐,久了不用之后便忘记了。前几天看知乎哪些Python库让你相见恨晚?,看到了yagmail第三方库,学习过程中遇到一些问题,记录在此处。

之前使用的python的smtplib、email模块发模块的一步步骤是:

一、先导入smtplib模块  导入MIMEText库用来做纯文本的邮件模板
二、发邮件几个相关的参数,每个邮箱的发件服务器不一样,以126为例子百度搜索服务器是 smtp.126.com
三、写邮件主题和正文,这里的正文是HTML格式的
四、最后调用SMTP发件服务

看下代码:
import uuidimport smtplibfrom email.mime.text import MIMEText#发邮件相关参数smtpsever = ‘smtp.126.com‘sender = ‘sender@126.com‘psw = "[email protected]"            #126邮箱授权码receiver = ‘receiver@qq.com‘#编辑邮件的内容# subject=u"NBA"body=str(uuid.uuid4())msg=MIMEText(body,‘html‘,‘utf-8‘)msg[‘from‘]=‘[email protected]‘msg[‘to‘]=‘userename@qq.com‘# msg[‘subject‘]=subjecttry:    smtp = smtplib.SMTP()    smtp.connect(smtpsever)    smtp.login(sender,psw)    smtp.sendmail(sender,receiver,msg.as_string())    print ("邮件发送成功")except smtplib.SMTPException:    print ("Error: 无法发送邮件")

要完成上面的邮件发送,需要以下信息:

1.发件服务器
2.发件人账号
3.发件人邮箱密码[指授权码]
4.收件人账号
5.编辑邮件内容[正文、从哪里、到哪里]
6.链接邮箱服务器
7.登录邮箱[提供发件人账号和密码(指授权码)]
8.发送邮件

看起来整个过程有那么一点点复杂,但是也还好吧,毕竟功能可以实现。。。

但是yagmail的出现会颠覆一些人对email的印象,因为yagmail对比email来说,实现上真的是太简单了,yagmail在Github上Home Page给出了yagmail的简单介绍以及使用。下面给出一个简洁的示例:

yagmail安装

pip install yagmail

技术分享图片

给单个接受者发送邮箱

import yagmail#链接邮箱服务器yag = yagmail.SMTP(user="[email protected]", 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([email protected]‘, ‘subject‘, contents)

发送结果如下:

技术分享图片

对比email、smtp模块,yagmail的实现真的是太简单了,感动的要哭了~~~~

给多个接受者发送邮件

# 发送邮件yag.send([‘[email protected]‘,‘[email protected]‘,‘[email protected]‘], ‘subject‘, contents)

在()内新增多个收件人的邮箱即可,其他参数不需要修改,是不是很简单~~~

发送带附件的邮件

yag.send(‘[email protected]‘, ‘发送附件‘, contents, ["E://whitelist.txt","E://baidu_img.jpg"])

上面的["E://whitelist.txt","E://baidu_img.jpg"]是上传附件的路径。返回结果如下:

技术分享图片

Python自动发邮件-yagmail库

评论关闭