Search code examples
pythongmailmime-mail

Gmail displays both HTML and text and HTML parts of email


I am sending an email to a gmail account using Python. This is the code I'm using

msg = email.mime.multipart.MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'HTML test'
msg_html = email.mime.text.MIMEText('<html><head></head><body><b>This is HTML</b></body></html>', 'html')
msg_txt = email.mime.text.MIMEText('This is text','plain')
msg.attach(msg_html)
msg.attach(msg_txt)
#SNIP SMTP connection code
smtpConn.sendmail('[email protected]', '[email protected]', msg.as_string())

When I view this email in gmail both the HTML and text version are shown like this:

This is HTML

This is text

It should be either displaying text or html, what causes this behavior.


Solution

  • The message is being sent as multipart/mixed (as this is the default) when it needs to be sent as multipart/alternative. mixed means that each part contains different content and all should be displayed, while alternative means that all parts have the same content in different formats and only one should be displayed.

    msg = email.mime.multipart.MIMEMultipart("alternative")
    

    Additionally, you should put the parts in increasing order of preference, i.e., text before HTML. The MUA (GMail in this case) will render the last part it knows how to display.

    See the Wikipedia article on MIME for a good introduction to formatting MIME messages.