简体   繁体   中英

Can't properly send HTML email with attached file via smtplib in python

I try to send email which contains text, html version of body and attached file. I use standart python example with additional code:

img = MIMEImage(some_image_file)
img.add_header('Content-Disposition','attachment; filename="file.jpg"')
msg.attach(text_body)
msg.attach(html_body)
msg.attach(img)

Gmail show my email well, however yandex.com' email client shows only attached picture without html or text body of the letter.

If I change order like that:

msg.attach(img)
msg.attach(html_body)

Yandex shows only html body of my letter, and do not show attachment!

Is there any additional headers I need to add in order to show my email correctly (html/txt body AND attached file) in any email clients?

After some research of email headers sent from normal email client, I found solution:

body = MIMEMultipart('alternative')
msg = MIMEMultipart('mixed')
....
body.attach(text_body)
body.attach(html_body)
msg.attach(body)
msg.attach(img)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM