9

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?

raphael
  • 2,762
  • 5
  • 26
  • 55
kainC
  • 400
  • 1
  • 3
  • 14
  • How big is the message? – Brandon Jewett-Hall Jun 28 '16 at 17:16
  • Even if I leave the string empty, or a couple of dozen lines, I still get the error. – kainC Jun 28 '16 at 23:37
  • Check this SO question [Failed sending mail through google api with javascript](http://stackoverflow.com/questions/30590988/failed-sending-mail-through-google-api-with-javascript) and [How to `insert` a `full` format message using the Gmail API?](http://stackoverflow.com/questions/26487630/how-to-insert-a-full-format-message-using-the-gmail-api) if it can help you. – KENdi Jun 29 '16 at 08:50
  • I was getting your error as well and managed to succeed with this answer – raphael Oct 10 '17 at 20:04

3 Answers3

6

I was able to get the example working by removing the changing create_message to:

create_message = {
        'raw': encoded_message
    }
Sero
  • 61
  • 1
  • 2
  • Although this is mentioned in document - create_message={'message':{'raw':encoded_message}}. However replacing it with create_message={'raw':encoded_message} does work in my case. – Vikas Naranje Jun 08 '22 at 07:57
3

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

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

just do:

...messages().send(body=message, userId='me'...
Jay Lee
  • 13,415
  • 3
  • 28
  • 59
0

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()}