python发送邮件(163邮箱):正文、图片、附件
#调用163邮箱实现邮件的发送,需要提前在163邮箱开启SMTP服务,获取授权码
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 发送邮件
class Mail:
def send_message(self, message=None, file=None, body_file=None, *images):
'''配置服务器信息'''
smtpsever = 'smtp.163.com'
# 设置端口
port = 25
# 发件人
sender = 'xxx@163.com'
# 授权码
token = 'xxxxx'
# 收件人
recevicer = 'xxx@qq.com'
msg = MIMEMultipart()
msg['from'] = sender
msg['to'] = recevicer
msg['subject'] = '测试报告' # 主题
# 正文
if message is None:
message = '测试用例运行最新日志如下:'
# 添加图片对象
i = 0
mime_images = []
img_info = ''
if not images is None:
for img in images:
i += 1
mime_img = MIMEImage(open(img, 'rb').read(), _subtype='octet-stream')
mime_img.add_header('Content-ID', 'imageid%d' % i)
mime_images.append('<p><img src="cid:imageid{0}" alt="imageid{0}"></p>'.format(i))
msg.attach(mime_img)
for t in mime_images:
img_info = img_info + str(t)
# 上传正文
mime_html = MIMEText('<html><body><p>{0}</p>{1}</body></html>'.format(message, img_info), 'html', 'utf-8')
msg.attach(mime_html)
else:
msg.attach(message)
# 将最新日志写入正文
if not body_file is None:
bf = GetPath().get_path(body_file)
with open(bf, 'r') as fb:
body = fb.read()
mime_text = MIMEText(body, 'html', 'utf8')
msg.attach(mime_text)
if not file is None:
# 读取文件内容
with open(file, 'rb') as fp:
file_upload = fp.read()
# 附件
file_name = str(file).split('/')
mf = MIMEText(file_upload, 'base64', 'utf8')
mf['Content-type'] = 'application/octet-stream'
mf['Content-Disposition'] = 'attachment;filename=%s' % file_name[-1]
msg.attach(mf)
# 发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtpsever, port)
smtp.login(sender, token)
smtp.sendmail(sender, recevicer, msg.as_string())
smtp.close()