4
votes

I am using the create draft function from googles API documentation:

https://developers.google.com/gmail/api/v1/reference/users/drafts/create

Whenever I send a message I get the following appear in my email message text when I go into gmail:

hello world
Date: Mon, 11 Sep 2017 15:31:19 +0200
Message-Id: <CAKPeGO69TbbigNFrK8T37fYgPzCfZwVf=p0gkvJbZF6duwWsdw@mail.gmail.com>
From: [email protected]

I don't know why I'm getting all of this text.

What I am trying to do is to create a draft email reply to an existing email but all I seem to get is a new draft with the text above (no to/from/subject fields populated).

Here's the function I'm using:

import base64
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import os

def CreateDraft(service, user_id, message_body):
   """Create and insert a draft email. Print the returned draft's message and id.

  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_body: The body of the email message, including headers.

  Returns:
    Draft object, including draft id and message meta data.
  """
    try:


        draft = service.users().drafts().create(userId=user_id, body=message_body).execute()

        print('Draft id: %s\nDraft message: %s' % (draft['id'], draft['message']))

        return draft

    except errors.HttpError as error:
        print('An error occurred: %s' % error)
        return None

And here's how I call it:

 gdraft.CreateDraft(service, user_id='me', message_body=
    {
        'message':
            {'raw': 'aGVsbG8gd29ybGQ=',
             'threadId': '15e5bdc650b1a068',
             'payload': {
                 "mimeType": "multipart/alternative",
                 "headers": [
                     {
                         "name": "In-Reply-To",
                         "value": "<16DCF6644C054E39B1F7F901BDD08EA2@[email protected]>"
                     },
                     {
                         "name": "References",
                         "value": '<16DCF6644C054E39B1F7F901BDD08EA2@[email protected]>'
                     },
                     {
                         "name": "Message-ID",
                         "value": "<16DCF6644C054E39B1F7F901BDD08EA2@[email protected]"
                     },
                     {
                         "name": "Subject",
                         "value": "Re: Software Developer - Hertford"
                     }
                 ]
             }
             }
    })

I have been trying now for four days without a success so I'd really appreciate any help.

UPDATE:

So it seems that I might need to use the createmessage function (based on the comments below); however this doesn't seem to work in Python3.

I changed:

return {'raw': base64.urlsafe_b64encode(message.as_string())}

to:

 return {'raw': str(base64.urlsafe_b64encode(message.as_string().encode("utf-8")))}

in an attempt to make it work but I am getting errors:

An error occurred: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/drafts?alt=json returned "Missing draft message">
1
I dont think that you've encoded the message. The docs seem to be using a MimeText class to wrap the message body and then encode it. The fields you've used also seem to be wrong. - Sachin
As body_message you have all the json value. This is the reason for why you are getting all information as body message. You have to use CreateMessage method to create your draft with information : to, from, Subject - attin83
I tried to use the create message function... but it doesn't form the message correctly. I get: An error occurred: <HttpError 400 when requesting googleapis.com/gmail/v1/users/me/drafts?alt=json returned "Missing draft message"> - It seems that the create message function tries to base64 encode the whole message rather than just the raw part. That being said I did modify the function to work with Python3. Perhaps I did that incorrectly. - K-Dawg
As suggested in this post, you need to use base64.urlsafe_b64encode(message.as_string()) with the url-safe base64 alphabet, otherwise you'll have invalid characters in your raw field. See: developers.google.com/gmail/api/v1/reference/users/messages/… for more information. - abielita
@abielita isn't that what I'm doing in already in the code above? - K-Dawg

1 Answers

3
votes

Thank you all for the comments you left. You were all right on different points.

The problem was that I was using a slightly different example to the one on the Docs page.

I found the code here worked: https://developers.google.com/gmail/api/guides/drafts

It can be used like so:

msg = create_message('[email protected]','[email protected]','Re: Some Subject','This is a test')

create_draft(service,'me',  msg)