Send HTML mail with Gmail API

·

1 min read

Again, TLDR; to send a HTML formatted text via gmail API, what you need is just a simple 'html' word to the MIMEText(). Here is the sample from the google developer site itself:

import base64
from email.mime.text import MIMEText
.....
def create_message(sender, to, subject, message_text):
  message = MIMEText(message_text)
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject
  return {'raw': base64.urlsafe_b64encode(message.as_string())}

And here is what you need to do:

import base64
from email.mime.text import MIMEText
.....
def create_message(sender, to, subject, message_text):
  message = MIMEText(message_text, 'html')
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject
  return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}

Also note that in the last return line, we need to modify by adding .encode() and decode(), otherwise you'd get the byte-str error. Here's how to use it for HTML message:

content = """
<b>Hello, there...</b>
<p>Enjoy this <u>html</u> content!</p>
"""
msg = create_message('me', 'target@email.com', 'test: send html mail', content)
message = (service.users().messages().send(userId='me', body=msg).execute())
print(message)

For the other things such as how to create the service, etc, you can find 'em in the google developer site.