python 发送邮件 Html内容嵌入图片 带附件

from email.header import Header
from email.mime.text import MIMEText
import smtplib
from email.utils import parseaddr, formataddr
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

def send_email(from_addr,password,to_addr,outfile,title,content,smtp_server="mail.wangsu.com"):
msg = MIMEMultipart()
msg['From'] = _format_addr(from_addr)
msg.add_header('To', to_addr)
subject = (title)
msg['Subject'] = Header(subject, 'utf-8')

hello = ("""
HI ALL:


  下表为{}
""".format(content))
msg.attach(MIMEText(('{}' +
'

' +
'').format(hello), 'html', 'utf-8'))

att1 = MIMEText(open(outfile, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'

这里的filename可以任意写,写什么名字,邮件中显示什么名字

filename = os.path.basename(outfile)
att1["Content-Type"] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
encoded_name = Header(filename).encode()
att1['Content-Disposition'] = 'attachment;filename="{}"'.format(encoded_name)
msg.attach(att1)

添加附件就是加上一个MIMEBase,从本地读取一个图片:

with open('jietu.png', 'rb') as f:
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase('image', 'png', filename='jietu.png')
# 加上必要的头信息:
mime.add_header('Content-Disposition', 'attachment', filename='jietu.png')
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)

server = smtplib.SMTP(smtp_server, 25)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr.split(","), msg.as_string())
server.quit()

你可能感兴趣的:(python 发送邮件 Html内容嵌入图片 带附件)