5. 带有附件的email
上面我们介绍了发送字符串的邮件,但这明显不满足现代邮件的需求,下面我们介绍如何发送内容以 HTML 格式,并且带有图片和文本文件的邮件。
处理多种形态的邮件主体我们需要 MIMEMultipart 类,而处理图片需要 MIMEImage 类。
import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.image import MIMEImage#设置登录及服务器信息mail_host = 'smtp.163.com'mail_user = '159*****02'mail_pass = '7******x'sender = '159*****02@163.com'receivers = ['7******0@qq.com']#设置eamil信息#添加一个MIMEmultipart类,处理正文及附件message = MIMEMultipart()message['From'] = sendermessage['To'] = receivers[0]message['Subject'] = 'title'#推荐使用html格式的正文内容,这样比较灵活,可以附加图片地址,调整格式等with open('abc.html','r') as f: content = f.read()#设置html格式参数part1 = MIMEText(content,'html','utf-8')#添加一个txt文本附件with open('abc.txt','r')as h: content2 = h.read()#设置txt参数part2 = MIMEText(content2,'plain',