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 am using
msg = email.mime.multipart.MIMEMultipart()
msg['From'] = 'myemail@gmail.com'
msg['To'] = 'toemail@gmail.com'
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('myemail@gmail.com', 'toemail@gmail.com', msg.as_string())
When I view this email in gmail, both the HTML and the text version are displayed like this:
This is HTML
This is the text
It should be either displaying text or html which is causing this behavior.
source to share
The message is sent as multipart/mixed
(as is the default ) when it needs to be sent as multipart/alternative
. mixed
means each part contains different content and everything should be displayed, which alternative
means that all parts have the same content in different formats and only one should be displayed.
msg = email.mime.multipart.MIMEMultipart("alternative")
Also, you must place the parts in ascending order, i.e. text before HTML. The MUA (GMail in this case) will display the last part it knows how to display.
See the Wikipedia article on MIME for a good introduction to formatting MIME messages.
source to share