Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Gmail Api Base64 Decode Strange Chars In Email Body

I'm using the Gmail API to retrieve emails from my inbox:

query = 'to:me after:{}'.format(weekStartDate)

unreadEmailsQuery = service.users().messages().list(userId='me', q=query).execute()

# For Each Email
for message in unreadEmailsQuery['messages']:
    result = service.users().messages().get(id=message['id'],userId='me').execute()
  email_content = ''
    
  if 'data' in result['payload']['body'].keys():
         email_content+= result['payload']['body']['data']
    else:

        for part in result['payload']['parts']:
            email_content = part['body']['data'] + email_content



    test = bytes(str(email_content),encoding='utf-8')
    print(base64.decodebytes(test))

prints out simple plain text messages correctly:

b'Got another one with me

But prints out HTML messages like this:

b'<body\x03B\x83B\x83B\x83B\x88\x08\x0f\x1bY]\x18H\x1a\x1d\x1d\x1c\x0bY\\]Z]\x8fH\x90\xdb\

I can see that it's okay until the first > from then on the string gets printed incorrectly and I'm not sure why.

I am trying to extract words out of my email so that I can train a classifier but I am stuck.

like image 273
K-Dawg Avatar asked Jul 17 '26 10:07

K-Dawg


1 Answers

I needed to use the URl safe base64 decoding.

I managed to get this working by changing the last line:

print(base64.decodebytes(test))

to:

print(base64.urlsafe_b64decode(test))
like image 108
K-Dawg Avatar answered Jul 18 '26 22:07

K-Dawg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!