博主有段时间没有更新博客了
先整理一个之前整理过的SMTP邮件发送,这次是带附件的功能
#!/usr/bin/env python
# -*- coding: utf_8 -*- from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import parseaddr, formataddr
import smtplib def _format_address(text):
name, address = parseaddr(text)
return formataddr((Header(name, "utf-8").encode(), address)) def unittest_smtp():
from_address = "xx@xx.com"
# 发件箱地址
password = "xxx"
# 授权密码 不是邮箱登录密码
to_address = "xx@xx.com"
# to_address = "xx@xx.com"
# 收件箱地址
smtp_server = "smtp.ym.163.com"
# 发件箱服务器地址
message = MIMEMultipart()
# msg = MIMEText("测试smtp邮件发送功能", "plain", "utf-8")
# 第一个参数:邮件正文
# 第二个参数:邮件类型 纯文本
# 第三个参数:编码 message["From"] = _format_address("自动化测试报告 <%s>" % from_address)
# 发件人姓名与地址
message["To"] = _format_address("xx <%s>" % to_address)
# 收件人姓名与地址
message["Subject"] = Header("xx自动化测试平台邮箱服务", "utf-8").encode()
# 邮件标题
message.attach(MIMEText("测试smtp邮件发送功能", "plain", "utf-8")) att1 = MIMEText(open("D:\\pythonproject\\Wito_erp\\wito_selenium\\20161024113212.html", "rb").read(), "base64", "utf-8")
# 文件地址
att1["Content-Type"] = "application/octet-stream"
att1["Content-Disposition"] = 'attachment; filename="20161024113212.html"'
# 定义附件名称 message.attach(att1)
# 添加附件
try:
server = smtplib.SMTP(smtp_server, 25)
# 构造smtp服务器连接
server.set_debuglevel(1)
# 打开debug输出模式
server.login(from_address, password)
# 登录smtp服务器
server.sendmail(from_address, to_address, message.as_string())
# 发送邮件 print "邮件发送成功"
server.quit()
except smtplib.SMTPException:
print "Error: 无法发送邮件"