5
votes

I am trying to send a message via the Google API in python, and am trying to run an example taken almost directly from the Google example page.

def CreateMessage(sender, to, subject, message_text):
    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    return {'raw': base64.urlsafe_b64encode(message.as_string().replace('message','resource').encode('ascii'))}

But when I try to send it

    message = CreateMessage(sender, to, subject, message_text)
    message = service.users().messages().send(body=list(message),userId='me').execute()

I get the error : "'raw' RFC822 payload message string or uploading message via /upload/* URL required"

From other posts it seems like Google is expecting an attachment. Is there something wrong with the MIMEText making it expect one, and if so, how do I fix it?

2
How big is the message? - Brandon Jewett-Hall
Even if I leave the string empty, or a couple of dozen lines, I still get the error. - kainC
I was getting your error as well and managed to succeed with this answer - raphael

2 Answers

2
votes

list(message) is not necessary and is giving the API a body of:

[{"raw": "b64 content..."}]

just do:

...messages().send(body=message, userId='me'...
0
votes

Please try the following :

msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = to
msg.attach(MIMEText(message_text, 'plain'))
return {'raw': base64.urlsafe_b64encode(msg.as_string().encode()).decode()}