如何使用html发送HTML电子邮件并附加图像?

时间:2019-06-17 20:20:21

标签: python email-attachments smtplib imghdr

我收到“错误:ValueError:无法将混合转换为替代”。

当我插入打开的图像和msg.add_attachment块时(在btw #### ####中突出显示),我收到此错误。没有它,代码运行良好。我需要将电子邮件发送为html并带有图片附件。

import os
import imghdr
from email.message import EmailMessage
import smtplib


EMAIL_ADDRESS = os.environ.get('EMAIL-USER')
EMAIL_PASSWORD = os.environ.get('EMAIL-PASS')

Message0 = "HelloWorld1"
Message1 = "HelloWorld2"

msg = EmailMessage()
msg['Subject'] = 'Hello WORLD'
msg['From'] = EMAIL_ADDRESS
msg['To'] = EMAIL_ADDRESS

msg.set_content('This is a plain text email, see HTML format')

########################################################################
with open('screenshot.png', 'rb') as f:
    file_data = f.read()
    file_type = imghdr.what(f.name)
    file_name = f.name

msg.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name)
#########################################################################

msg.add_alternative("""\
    <!DOCTYPE html>
    <html>
        <body>
            <h1 style="color:Blue;">Hello World</h1>
                {Message0}
                {Message1}
        </body>
    </html>
    """.format(**locals()), subtype='html')

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
    smtp.send_message(msg)
    print("email sent")

0 个答案:

没有答案