#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 发送带有附件的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
# 配置
HOST = 'smtp.qq.com'
PORT = 465
SUBJECT = '测试邮件'
FROM = '123456789@qq.com'
TO = '987654321@qq.com'
message = MIMEMultipart('related') # related: 邮件内容的格式,采用内嵌的形式进行展示
message_html = MIMEText('<h1>含有图片的邮件</h1><img src="cid:images">', 'html', 'utf-8') # 向message对象中添加不同类型的邮件内容,发送的内容是html的邮件,邮件中含有图片,参数2:指定邮件内容类型,默认是plain,表示没有任何格式的纯文本
message.attach(message_html) # 需要将message_html对象,添加至message中,等待被传送
# 发送带有图片html(加载图片, rb:二进制输出)
def load_image(path, cid):
data = open(path, 'rb')
message_img = MIMEImage(data.read())
data.close()
message_img.add_header('Content-ID', cid)
return message_img
message.attach(load_image('2.jpg', 'images'))
# 发送附件
message_docx = MIMEText(open('config.py', 'rb').read(), 'base64', 'utf8')
message_docx.add_header('contnet-disposition', 'attachment', filename='测试.docx')
message.attach(message_docx)
# 发送附件图片
message_img = MIMEText(open('2.jpg', 'rb').read(), 'base64', 'utf8')
message_img.add_header('content-disposition', 'attachment', filename='尤克里里.jpg')
message.attach(message_img)
message['From'] = FROM
message['Subject'] = SUBJECT
message['To'] = TO
smtp_obj = smtplib.SMTP_SSL()
smtp_obj.connect(host=HOST, port=PORT)
# 授权码
res = smtp_obj.login(FROM, 'prhfjastbaaj')
print('登录结果: ', res)
re = smtp_obj.sendmail(from_addr=FROM, to_addrs=[TO], msg=message.as_string())
print('发送结果: ', re)