# -*- coding: utf-8 -*-
#设置服务器所需信息
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail_host = 'smtp.qq.com'
mail_user = '384436100@qq.com'
#密码(部分邮箱为授权码) jyoflcxdztcwbghb
mail_pass = '#############'
#邮件发送方邮箱地址
sender = '384436100@qq.com'
#邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receivers = ['libaowenflipper@foxmail.com']
#设置email信息
#邮件内容设置
message = MIMEMultipart()
#邮件主题
message['Subject'] = '测试python带图片附件邮件'
#邮件正文 方式1:直接在写html内容
mail_body = '''
<h5>hello,同学们</h5>
<p>
上课吃饭打豆豆
</p>
<p><img src="cid:image1"></p>
'''
#邮件正文 方式2:直接读取html内容
with open('测试.html','r',encoding='UTF-8') as f:
content = f.read()
part1 = MIMEText(content,'html','utf-8')
#添加txt附件
with open('python.txt','r',encoding='UTF-8')as h:
content2 = h.read()
part2 = MIMEText(content2,'plain','utf-8')
#附件设置内容类型,方便起见,设置为二进制流
part2['Content-Type'] = 'application/octet-stream'
#设置附件头,添加文件名
part2['Content-Disposition'] = 'attachment;filename="python.txt"'
#添加照片附件
with open('美女.jfif','rb')as fp:
fp = open('美女.jfif', 'rb')
picture = MIMEImage(fp.read())
#与txt文件设置相似
picture['Content-Type'] = 'application/octet-stream'
picture['Content-Disposition'] = 'attachment;filename="美女.png"'
#将内容附加到邮件主体中
msgAlternative = MIMEMultipart('alternative')
msgAlternative.attach(MIMEText(mail_body, 'html', 'utf-8'))
message.attach(msgAlternative) # 把邮件正?内容添加到msg_root?
message.attach(part1)
message.attach(part2)
message.attach(picture)
# 定义图? ID,在 HTML ?本中引?
fp = open('美女.jfif', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
message.attach(msgImage) # 添加图?到msg_root对象?
#发送方信息
message['From'] = sender
#接受方信息
message['To'] = receivers[0]
#登录并发送邮件
try:
smtpObj = smtplib.SMTP()
#连接到服务器
smtpObj.connect(mail_host,25)
smtpObj = smtplib.SMTP_SSL(mail_host)
#登录到服务器
smtpObj.login(mail_user,mail_pass)
smtpObj.set_debuglevel(1) # 显示调试信息
#发送
smtpObj.sendmail(sender,receivers,message.as_string())
#退出
smtpObj.quit()
print('success')
except smtplib.SMTPException as e:
print('error',e) #打印错误
#报错:ModuleNotFoundError: No module named 'email.mime'; 'email' is not a package
#解决办法:包名和文件名冲突
#报错:Python读取文件时出现UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position xx: 解决方案
#with open('article.txt','r',encoding='UTF-8') as f: # 打开新的文本
效果:
?
|