Search code examples
pythonemailgmailhtml-emailimaplib

How can I create HTML email drafts in Gmail using Python?


I can successfully create plaintext email drafts in Gmail using this snippet:

from email.message import Message
import imaplib
import time

message = Message()

    # Create message
    message["To"] = "john.doe@gmail.com"
    message["Subject"] = "Subject line"
    message.set_payload("This is the email <a href=#>body</a>")
    utf8_message = str(message).encode("utf-8")

    # Send message
    status, data = imap_ssl.append('"[Google Mail]/Drafts"', "", imaplib.Time2Internaldate(time.time()), utf8_message)

However, it displays as:

This is the email <a href=#>body</a>

Is there a way to get it to display as this?

This is the email body

I've tried playing with MIMEText, which I can successfully use to send HTML emails via smtplib, but I'm not sure if it's possible with imaplib.


Solution

  • Just add a content-type header

        message["Content-Type"] = "text/html;charset=UTF-8"