Loading

Python学习--21 电子邮件

发送邮件

SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

Python对SMTP支持有smtplibemail两个模块,email负责构造邮件,smtplib负责发送邮件。

发送简单邮件

下面是最简单的发邮件的例子:

# coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 连接邮件服务器
mail_host = 'smtp.163.com'
mail_port = '25'
mail_from = 'xxx@163.com'
smtp = smtplib.SMTP()
# smtp.set_debuglevel(1) # 打印出和SMTP服务器交互的所有信息
smtp.connect(mail_host, mail_port)
smtp.login(mail_from, 'xxx')

# 构造邮件对象
msg = MIMEText('Python测试', 'plain', 'utf-8')
msg['From'] = mail_from
msg['To'] = 'xxx@qq.com'
msg['Subject'] = Header('测试邮件', 'utf-8')

# 发送邮件
smtp.sendmail(mail_from, 'xxx@qq.com', msg.as_string())
smtp.quit()

注意默认msg['From']msg['To']都是邮箱格式。msg['From']可以和发件邮箱不一致,即使是不存在的邮箱,例如'yjc@test.com',会显示是代发的。

如果想要将msg['From']改为中文的,需要编码:

# coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

# 连接邮件服务器
mail_host = 'smtp.163.com'
mail_port = '25'
mail_from = 'xxx@163.com'
smtp = smtplib.SMTP()
smtp.connect(mail_host, mail_port)
smtp.login(mail_from, 'xxx')

# 构造邮件对象
msg = MIMEText('Python测试', 'plain', 'utf-8')
msg['From'] = _format_addr('Python爱好者 <%s>' % mail_from)
msg['To'] = _format_addr('管理员 <%s>' % 'xxx@qq.com')
msg['Subject'] = Header('测试邮件', 'utf-8')

# 发送邮件
smtp.sendmail(mail_from, 'xxx@qq.com', msg.as_string())
smtp.quit()

发送HTML格式的邮件

Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html。

很简单,只需要把实例化邮件对象那句简单修改:

msg = MIMEText('<h1 style="color:red;">Python测试</h1>', 'html', 'utf-8')

再次发送就可以看到效果了。支持内联CSS。

发送附件

发送附件就需要把真个邮件当做复合型的内容:文本和各个附件本身。通过构造一个MIMEMultipart对象代表邮件本身,然后往里面加上一个MIMEText作为邮件正文,再继续往里面加上附件部分:

# coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

# 连接邮件服务器
mail_host = 'smtp.163.com'
mail_port = '25'
mail_from = 'xxx@163.com'
smtp = smtplib.SMTP()
smtp.connect(mail_host, mail_port)
smtp.login(mail_from, 'xxx')

# 构造邮件对象
msg = MIMEMultipart()
msg['From'] = mail_from
msg['To'] = 'xxx@qq.com'
msg['Subject'] = Header('测试邮件', 'utf-8')
msg.attach(MIMEText('Python测试', 'plain', 'utf-8')) #邮件正文

## 附件
att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream' # 二进制流,不知道下载文件类型
att1["Content-Disposition"] = 'attachment; filename="test.txt"' # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
msg.attach(att1)

att2 = MIMEText(open('test.jpg', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'image/jpeg'
att2["Content-Disposition"] = 'attachment; filename="test.jpg"'
msg.attach(att2)

smtp.sendmail(mail_from, 'xxx@qq.com', msg.as_string())
smtp.quit()

这里将二进制文件读入并转成base64编码,添加到邮件中。需要注意的是,Content-Type指文件的Mime-Type,例如纯文本是text/plain,jpg是image/jpeg,如果不知道类型,则统称为application/octet-stream

最后需要注意的是,发送邮件部分最好使用try...except...语句:

try:
    smtp = smtplib.SMTP('localhost')
    smtp.sendmail(sender, receivers, msg.as_string())
    print "邮件发送成功"
except smtplib.SMTPException:
    print "Error: 无法发送邮件"

参考:
1、SMTP发送邮件 - 廖雪峰的官方网站
http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432005226355aadb8d4b2f3f42f6b1d6f2c5bd8d5263000
2、Python SMTP发送邮件 | 菜鸟教程
http://www.runoob.com/python/python-email.html
3、HTTP Content-type 对照表
http://tool.oschina.net/commons

posted @ 2017-02-15 18:35  飞鸿影  阅读(775)  评论(1编辑  收藏  举报