2

In my script I need to extract a set of emails that match some query. I decided to use GMail's API python client for this. Now, my understanding was that the GetMimeMessage() was supposed to return a set of decoded base 64 messages. Here is my code:

def GmailInput():

    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    defaultList= ListMessagesMatchingQuery(service, 'me', 'subject:infringement label:unread ')
    print(defaultList)
    for msg in defaultList:
        currentMSG=GetMimeMessage(service, 'me', msg['id'])
        ....then I parse the text of the emails and extract some things

The problem is, I am unable to actually parse the message body because GetMimeMessage is not returning a base64 decoded message. So what I am actually parsing ends up being completely unreadable by humans.

I find this peculiar because GetMimeMessage (copied below for convenience) literally does a url-safe base 64 decode of the message data. Anyone have any suggestion? Im really stumped on this.

def GetMimeMessage(service, user_id, msg_id):
  """Get a Message and use it to create a MIME 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.
    msg_id: The ID of the Message required.

  Returns:
    A MIME Message, consisting of data from Message.
  """
  try:
    message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()

    print ('Message snippet: %s' % message['snippet'])

    msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))

    mime_msg = email.message_from_string(msg_str)

    return mime_msg
  except errors.HttpError, error:
    print ('An error occurred: %s' % error)
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
Andras Palfi
  • 206
  • 3
  • 12
  • Have you tried pinging the people working on the python client library? – Linda Lawton - DaImTo Jun 28 '16 at 17:36
  • I have posted it to the Google API Python Google Group but no luck yet :/ – Andras Palfi Jun 28 '16 at 17:56
  • 1
    Try here https://github.com/google/google-api-python-client/issues – Linda Lawton - DaImTo Jun 28 '16 at 17:57
  • So what do you end up with, and why do you think it's wrong? I have no experience with this API but from reading the doc, I don't see why you expiect the message itself to be decoded. In other words, if you get a message with `Content-transfer-encoding: base64` then that's what the original message looked like, so that's what you'll get (though the API will apparently have wrapped it in *another layer of* base64 for API transport which is decoded and gone now). – tripleee Dec 31 '17 at 20:46
  • Here I posted a full tutorial on the subject https://stackoverflow.com/questions/24428246/retrieve-email-message-body-in-html-using-gmail-api/57064505#57064505 – Roberto Rodriguez Jul 16 '19 at 19:52

1 Answers1

0

You can use User.messages:get. This request requires authorization with at least one of the following scopes.

HTTP request

GET https://www.googleapis.com/gmail/v1/users/userId/messages/id

import base64
import email
from apiclient import errors

def GetMessage(service, user_id, msg_id):
"""Get a Message with given 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.
msg_id: The ID of the Message required.

Returns:
A Message.
"""
try:
message = service.users().messages().get(userId=user_id, id=msg_id).execute()

print 'Message snippet: %s' % message['snippet']

return message
except errors.HttpError, error:
print 'An error occurred: %s' % error


def GetMimeMessage(service, user_id, msg_id):
"""Get a Message and use it to create a MIME 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.
msg_id: The ID of the Message required.

Returns:
A MIME Message, consisting of data from Message.
"""
try:
message = service.users().messages().get(userId=user_id, id=msg_id,
format='raw').execute()

print 'Message snippet: %s' % message['snippet']

msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))

mime_msg = email.message_from_string(msg_str)

return mime_msg
except errors.HttpError, error:
print 'An error occurred: %s' % error
Android Enthusiast
  • 4,826
  • 2
  • 15
  • 30
  • Yes, if you see in my post above I am using this exact GetMimeMessage function. But this function is supposed to be returning a decoded version of the message, but when I run it, it is still in base 4 encoded version and that is the problem – Andras Palfi Jun 29 '16 at 14:34