python学习笔记(SMTP邮件发送:带附件)

博主有段时间没有更新博客了

先整理一个之前整理过的SMTP邮件发送,这次是带附件的功能

 1 #!/usr/bin/env python
 2 # -*- coding: utf_8 -*-
 3 
 4 from email.mime.text import MIMEText
 5 from email.mime.multipart import MIMEMultipart
 6 from email.header import Header
 7 from email.utils import parseaddr, formataddr
 8 import smtplib
 9 
10 
11 def _format_address(text):
12     name, address = parseaddr(text)
13     return formataddr((Header(name, "utf-8").encode(), address))
14 
15 
16 def unittest_smtp():
17     from_address = "xx@xx.com"
18     # 发件箱地址
19     password = "xxx"
20     # 授权密码 不是邮箱登录密码
21     to_address = "xx@xx.com"
22     # to_address = "xx@xx.com"
23     # 收件箱地址
24     smtp_server = "smtp.ym.163.com"
25     # 发件箱服务器地址
26     message = MIMEMultipart()
27     # msg = MIMEText("测试smtp邮件发送功能", "plain", "utf-8")
28     # 第一个参数:邮件正文
29     # 第二个参数:邮件类型 纯文本
30     # 第三个参数:编码
31 
32     message["From"] = _format_address("自动化测试报告 <%s>" % from_address)
33     # 发件人姓名与地址
34     message["To"] = _format_address("xx <%s>" % to_address)
35     # 收件人姓名与地址
36     message["Subject"] = Header("xx自动化测试平台邮箱服务", "utf-8").encode()
37     # 邮件标题
38     message.attach(MIMEText("测试smtp邮件发送功能", "plain", "utf-8"))
39 
40     att1 = MIMEText(open("D:\\pythonproject\\Wito_erp\\wito_selenium\\20161024113212.html", "rb").read(), "base64", "utf-8")
41     # 文件地址
42     att1["Content-Type"] = "application/octet-stream"
43     att1["Content-Disposition"] = 'attachment; filename="20161024113212.html"'
44     # 定义附件名称
45 
46     message.attach(att1)
47     # 添加附件
48     try:
49         server = smtplib.SMTP(smtp_server, 25)
50         # 构造smtp服务器连接
51         server.set_debuglevel(1)
52         # 打开debug输出模式
53         server.login(from_address, password)
54         # 登录smtp服务器
55         server.sendmail(from_address, to_address, message.as_string())
56         # 发送邮件
57 
58         print "邮件发送成功"
59         server.quit()
60     except smtplib.SMTPException:
61         print "Error: 无法发送邮件"

 

posted on 2016-10-24 16:35  堕落的伊丝莉  阅读(678)  评论(0编辑  收藏  举报