封装邮件发送,用于发送测试报告
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import mimetypes
import os
class SendEmail(object):
# 创建SMTP对象(用途为发送邮件)
# 连接邮件服务器
# 登录
# 发送邮件请求(邮件内容通过email模块构造邮件)
# 退出
def __init__(self, host="smtp.163.com", user="jj_wu1991@163.com", pwd="XXXXXX"):
self.mail_host = host #服务器
self.user_sender = user #用户名
self.pwd = pwd #密码
def send(self, receivers, subject, content, msg_type="html", attachment=[]):
msg = MIMEMultipart()
msg["To"] = receivers
msg["Subject"] = Header(subject, "utf-8")
# 正文
msg.attach(MIMEText(content, msg_type, "utf-8"))
# 添加附件
for address in attachment:
with open(address, "rb") as f:
ctype, encoding = mimetypes.guess_type(address)
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
mime = MIMEBase(maintype, subtype, filename=os.path.basename(address))
mime.add_header('Content-Disposition', 'attachment', filename=os.path.basename(address))
# mime.add_header('Content-ID', '<0>')
# mime.add_header('X-Attachment-Id', '0')
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
try:
smtpObj = smtplib.SMTP()
# smtpObj.set_debuglevel(1)
smtpObj.connect(self.mail_host)
smtpObj.login(self.user_sender, self.pwd)
smtpObj.sendmail(self.user_sender, receivers.split(","), msg.as_string())
smtpObj.quit()
print "邮件发送成功"
except smtplib.SMTPException as e:
print "Error:发送邮件失败"
print e.args[0], e.args[1]
if __name__ == '__main__':
sendemail = SendEmail()
sendemail.send("jj_wu1991@163.com", "标题", "测试测试",
attachment=["C:/Users/Administrator/Pictures/1.jpg"])