OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How do I send HTML Formatted emails, through the gmail-api for python

  • Thread starter Thread starter Andrew
  • Start date Start date
A

Andrew

Guest
Using the sample code from the GMail API Example: Send Mail, and after following rules for authentication, it's simple enough to send a programmatically generated email, via a gmail account. What isn't obvious from the example is how to set that email to be HTML formatted.


The Question​


How do I get HTML formatting in my gmail-api send messages, using python?

I have this...​


message_body = "Hello!\nYou've just received a test message!\n\nSincerely,\n-Test Message Generator\n"

and I want it to be this...​


Code:
Hello!
You've just received a test message!

Sincerely,
-Test Message Generator

Example Source Code from GMail-API​


Below is a slightly modified version of the example, but still works:

Code:
import argparse
import base64
from pprint import pformat
from pprint import pprint
import httplib2
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage


SCOPES = 'https://mail.google.com/'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Test EMail App'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """

    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def create_message(sender, to, cc, subject, message_text):
    """Create a message for an email.

    Args:
    sender: Email address of the sender.
    to: Email address of the receiver.
    subject: The subject of the email message.
    message_text: The text of the email message.

    Returns:
    An object containing a base64url encoded email object.
    """
    print(sender + ', ' + to + ', ' + subject + ', ' + message_text)
    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    message['cc'] = cc
    pprint(message)
    return {'raw': base64.urlsafe_b64encode(message.as_string())}

def send_message(service, user_id, message_in):
    """Send an email message.

    Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    message: Message to be sent.

    Returns:
    Sent Message.
    """
    pprint(message_in)
    try:
        message = (service.users().messages().send(userId=user_id, body=message_in).execute())
        pprint(message)
        print ('Message Id: %s' % message['id'])
        return message
    except errors.HttpError, error:
        print ('An error occurred: %s' % error)

def main(cli):
    """Shows basic usage of the Gmail API.

    Creates a Gmail API service object and outputs a list of label names
    of the user's Gmail account.
    """


    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)

    email_msg = create_message(cli.addr_from, cli.addr_to, cli.addr_cc, cli.subject, cli.message)
    msg_out = service.users().messages().send(userId = 'me', body = email_msg).execute()
    pprint(msg_out)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-m', '--message',   help = 'The message to send in the email', default='<MESSAGE = unfinished>')
    parser.add_argument('-t', '--addr_to',   help = 'the list of comma separated emails to send', default='[email protected]')
    parser.add_argument('-s', '--subject',   help = 'the email subject', default='<SUBJECT = undefined>')
    parser.add_argument('-c', '--addr_cc',   help = 'email CC\'s', default='')
    parser.add_argument('-f', '--addr_from', help = 'Email address to send from', default='[email protected]')
    cli = parser.parse_args()
    pprint(dir(cli))

    main(cli)

Tried as I might, with this code, and variations on it, I could not get html formatted code, nor could I get simple escape characters to create carriage returns where they needed to be.


Here's what didn't work​


Trying the following didn't work either:

  1. modifying line 69 to add additional message dictionary parameters... ie.
    • {'raw': base64.urlsafe_b64encode(message.as_string()), 'payload': {'mimeType': 'text/html'}}
    • As documented here in the GMail API Docs
    • enter image description here
  2. Adding a variety of escaped backslashes into the message text:
    • \n... ie: \\n nor \\\n and just rendered as those exact characters
    • Adding <br> </br> <br/> did not add new lines and just rendered as those exact characters
    • Adding \r did not add new lines and just rendered as that exact character

Reasons this is not a duplicate question​

<p>Using the sample code from the <a href="https://developers.google.com/gmail/api/v1/reference/users/messages/send" rel="noreferrer">GMail API Example: Send Mail</a>, and after following rules for authentication, it's simple enough to send a programmatically generated email, via a gmail account. What isn't obvious from the example is how to set that email to be HTML formatted.</p>

<hr>

<h2>The Question</h2>

<p><strong>How do I get HTML formatting in my gmail-api send messages, using python?</strong></p>

<h3>I have this...</h3>

<p><code>message_body = "Hello!\nYou've just received a test message!\n\nSincerely,\n-Test Message Generator\n"</code></p>

<h3>and I want it to be this...</h3>

<pre><code>Hello!
You've just received a test message!

Sincerely,
-Test Message Generator
</code></pre>

<hr>

<h2>Example Source Code from GMail-API</h2>

<p>Below is a slightly modified version of the example, but still works:</p>

<pre><code>import argparse
import base64
from pprint import pformat
from pprint import pprint
import httplib2
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage


SCOPES = 'https://mail.google.com/'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Test EMail App'


def get_credentials():
"""Gets valid user credentials from storage.

If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.

Returns:
Credentials, the obtained credential.
"""

home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'gmail-python-quickstart.json')

store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials

def create_message(sender, to, cc, subject, message_text):
"""Create a message for an email.

Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.

Returns:
An object containing a base64url encoded email object.
"""
print(sender + ', ' + to + ', ' + subject + ', ' + message_text)
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
message['cc'] = cc
pprint(message)
return {'raw': base64.urlsafe_b64encode(message.as_string())}

def send_message(service, user_id, message_in):
"""Send an email message.

Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.

Returns:
Sent Message.
"""
pprint(message_in)
try:
message = (service.users().messages().send(userId=user_id, body=message_in).execute())
pprint(message)
print ('Message Id: %s' % message['id'])
return message
except errors.HttpError, error:
print ('An error occurred: %s' % error)

def main(cli):
"""Shows basic usage of the Gmail API.

Creates a Gmail API service object and outputs a list of label names
of the user's Gmail account.
"""


credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)

email_msg = create_message(cli.addr_from, cli.addr_to, cli.addr_cc, cli.subject, cli.message)
msg_out = service.users().messages().send(userId = 'me', body = email_msg).execute()
pprint(msg_out)


if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--message', help = 'The message to send in the email', default='<MESSAGE = unfinished>')
parser.add_argument('-t', '--addr_to', help = 'the list of comma separated emails to send', default='[email protected]')
parser.add_argument('-s', '--subject', help = 'the email subject', default='<SUBJECT = undefined>')
parser.add_argument('-c', '--addr_cc', help = 'email CC\'s', default='')
parser.add_argument('-f', '--addr_from', help = 'Email address to send from', default='[email protected]')
cli = parser.parse_args()
pprint(dir(cli))

main(cli)
</code></pre>

<p>Tried as I might, with this code, and variations on it, I could not get html formatted code, nor could I get simple escape characters to create carriage returns where they needed to be.</p>

<hr>

<h2>Here's what didn't work</h2>

<p>Trying the following didn't work either:</p>

<ol>
<li>modifying <code>line 69</code> to add additional message dictionary parameters... ie.

<ul>
<li><code>{'raw': base64.urlsafe_b64encode(message.as_string()), 'payload': {'mimeType': 'text/html'}}</code></li>
<li>As documented here in the <a href="https://developers.google.com/gmail/api/v1/reference/users/messages" rel="noreferrer">GMail API Docs</a></li>
<li><a href="https://i.sstatic.net/zhI0l.png" rel="noreferrer"><img src="https://i.sstatic.net/zhI0l.png" alt="enter image description here"></a></li>
</ul></li>
<li>Adding a variety of escaped backslashes into the message text:

<ul>
<li><code>\n</code>... ie: <code>\\n</code> nor <code>\\\n</code> and just rendered as those exact characters</li>
<li>Adding <code><br> </br> <br/></code> did not add new lines and just rendered as those exact characters</li>
<li>Adding <code>\r</code> did not add new lines and just rendered as that exact character</li>
</ul></li>
</ol>

<hr>

<h2>Reasons this is not a duplicate question</h2>

<ul>
<li><a href="https://stackoverflow.com/questions/26841905/sending-email-multipart-signed-rfc-3156-via-gmail-apis">This SO link deals with multipart/signed messages</a>

<ul>
<li>I am uninterested in multipart messaging because it is an inelegant solution. I want the WHOLE message to be <code>HTML</code>. </li>
<li>Additionally, this link has no accepted answer, and the one answer present is a non-answer as it simply states that they are sending a problem statement to Google.</li>
</ul></li>
<li>This one deals with c#, which I am not interested in since I'm writing in python

<ul>
<li><a href="https://stackoverflow.com/questions/8628683/how-to-send-html-formatted-email">This one also uses SMTP which I'm not interested in</a></li>
</ul></li>
<li><a href="https://stackoverflow.com/questions...ain-text-email-instead-html?noredirect=1&lq=1">This one is for Rails</a></li>
</ul>
 
Top