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

时间:2019-08-23 01:46:29

标签: python email-attachments smtplib

我收到一个“错误: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")

为获得最终结果,我需要能够通过Python发送电子邮件并附加图像。

1 个答案:

答案 0 :(得分:0)

电子邮件可以由单个部分组成,也可以是多部分消息。 如果是多部分邮件,则通常为multipart/alternativemultipart/mixed

  • multipart/alternative 表示相同内容有2个或更多版本(例如纯文本和html)
  • multipart/mixed 用于需要将多个不同的内容(例如电子邮件和附件)打包在一起的情况。

使用multipart时实际发生的情况是电子邮件由“多部分”容器组成,该容器包含其他部分,例如对于text + html,它是这样的:

  • multipart/alternative部分
    • text/plain部分
    • text/html部分

对于带有附件的电子邮件,您可以输入以下内容:

  • multipart/mixed部分
    • text/plain部分
    • image/png部分

因此,容器是mixedalternative,但不能两者都是。那么,如何兼得呢?您可以嵌套它们,例如:

  • multipart/mixed部分
    • multipart/alternative部分
      • text/plain部分
      • text/html部分
    • image/png部分

因此,现在您有一封电子邮件,其中包含一条消息和一个附件,并且该消息同时具有纯文本和html。


现在,在代码中,这是基本概念:

msg = EmailMessage()
msg['Subject'] = 'Subject'
msg['From'] = 'from@email'
msg['To'] = 'to@email'

msg.set_content('This is a plain text')
msg.add_attachment(b'xxxxxx', maintype='image', subtype='png', filename='image.png')

# Now there are plain text and attachment.
# HTML should be added as alternative to the plain text part:

text_part, attachment_part = msg.iter_parts()
text_part.add_alternative("<p>html contents</p>", subtype='html')

顺便说一句,然后您可以通过这种方式查看每个部分的内容:

>>> plain_text_part, html_text_part = text_part.iter_parts()
>>> print(plain_text_part)
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit

This is a plain text

>>> print(html_text_part)
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0

<p>html contents</p>

>>> print(attachment_part)
Content-Type: image/png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="image.png"
MIME-Version: 1.0

eHh4eHh4

>>> print(msg)
Subject: Subject
From: from@email
To: to@email
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="===============2219697219721248811=="

--===============2219697219721248811==
Content-Type: multipart/alternative;
 boundary="===============5680305804901241482=="

--===============5680305804901241482==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit

This is a plain text

--===============5680305804901241482==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0

<p>html contents</p>

--===============5680305804901241482==--

--===============2219697219721248811==
Content-Type: image/png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="image.png"
MIME-Version: 1.0

eHh4eHh4

--===============2219697219721248811==--