Google gmail API: base64 needs bytes but URL body needs str

Viewed 198

I am working through this Google Gmail API tutorial (really I am skimming it to send an email). The body of my email must be encoded MIMEText & base64 but the contents of 'raw' property of a JSON payload must be a string. This leads me to a 'rock in a hard place' with 2 errors. Here is the code following the tutorial:

message = MIMEText(RecipData["EmailText"])

message['to'] = RecipData["Email"]

message['from'] = SENDER

message['subject'] = Subject

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

service.users().messages().send(userId=SENDER, body=EncodedMessage).execute()

I get the following error:

TypeError: a bytes-like object is required, not 'str'

Now if I change this line:

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

To:

EncodedMessage = {'raw': base64.urlsafe_b64encode(message.as_bytes())}

Then I get an error of:

TypeError: Object of type bytes is not JSON serializable

Not sure what I should do to get around this? Any suggestions? Thanks.

1 Answers

Here what I ended up doing. I converted the MIMEText to a byte so that it would work inside base64.urlsafe_b64encode() then I used str() so the data would fit into JSON. But, the str() needed to be stripped of is b'...' which was wrapped into the string.

message = base64.urlsafe_b64encode(bytes(message))

message = {'raw': str(message).strip('b').strip('\'')}
print(service.users().messages().send(userId="me", body=message).execute())  
Related