Skip to content
Advertisement

Python – How to send an html email and attach an image with Python?

I am getting an “error: ValueError: Cannot convert mixed to alternative.”

I get this error when I insert the open image and msg.add_attachment block (highlighted in btw #### ####). Without it, the code runs fine. I need to send the email as html and with the image attachment.

JavaScript

For the end result, I need to be able to send an email via Python and attach images.

Advertisement

Answer

An e-mail can consist of a single part, or it can be a multi-part message. If it is a multi-part message, it will usually be either a multipart/alternative, or a multipart/mixed.

  • multipart/alternative means there are 2 or more versions of the same content (e.g. plain text and html)
  • multipart/mixed is used when multiple different contents need to be packed together (e.g. an email and an attachment)

What actually happens when multipart is used is that email consists of a “multipart” container which contains additional parts, e.g. for text+html it is something like this:

  • multipart/alternative part
    • text/plain part
    • text/html part

In case of an email with attachment, you can have something like this:

  • multipart/mixed part
    • text/plain part
    • image/png part

So, the container is either mixed or alternative, but cannot be both. So, how to have both? You can nest them, e.g.:

  • multipart/mixed part
    • multipart/alternative part
      • text/plain part
      • text/html part
    • image/png part

So, now you have an email which consists of a message and an attachment, and the message has both plain text and html.


Now, in code, this is the basic idea:

JavaScript

BTW, you can then see what is in each part this way:

JavaScript

JavaScript

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement