python实战之一发送电子邮件

把曾经做过的东西做下小结吧。
如何来使用python发送电子邮件呢?

一般而言,官方提供的思路就是使用smtplib包,但是实现起来个人感觉还是稍显复杂,需要按照要求书写好多比如smtp mime 手动添加邮件头,还需要一些email标准的某些知识。
like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/python
#-*- coding: utf-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

sender = 'z.j19910903@163.com'# 发件人
to = ["815012839@qq.com", "a@qq.com"] # 多个收件人的写法
subject = 'From Python Email test'# 邮件主题
smtpserver = 'smtp.163.com'# smtp服务器
username = 'z.j19910903'# 发件人邮箱用户名
password = '******'# 发件人邮箱密码
mail_postfix = '163.com'
contents = '这是一个Python的邮件,收到请勿回复,谢谢!!'

def send_mail(to_list, sub, content):
me = sender
msg = MIMEText(content, _subtype='plain', _charset='utf-8')
msg['Subject'] = subject
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(smtpserver)
server.login(username, password)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False

if __name__ == '__main__':
if send_mail(to, subject, contents):
print "邮件发送成功! "
else:
print "失败!!!"

可能看起来也不是很多,但是还是感觉稍稍有点麻烦。python让人着迷的地方,就是有大量的优秀开发人员开发的各种第三方库,现在我们需要的只是yagmail。


##yagmail
安装不多说,直接pip

pip install yagmail

它支持python2.7+

使用的话也相对简单

import yagmail
yag = yagmail(zhangjohn202@gmail.com,'your2-steppassword')
contents='i love you more!'
yag.send(to='815012839@qq.com',subject='fall love at first sight',contents=contents)

这里说下,一般的邮箱都是用户名和登录密码,别的邮箱我不知道现在有多少改进,感觉gmail不愧是属于全人类的邮箱,这里采用更为安全的方式来进行登录,两步验证密码。

自然只是最简单的举例,yagmail实现的功能还有富文本邮件 邮件附件以及使用邮件模板这较为常见的三项,详细可以参考yagmail的github主页。