使用Google API发送邮件时出错 - "' raw' RFC822有效负载消息字符串或通过/ upload / * URL上传消息"

时间:2016-06-28 00:45:00

标签: python-3.x gmail-api google-api-python-client

我正在尝试通过python中的Google API发送消息,并尝试运行几乎直接来自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'))}

但是当我尝试发送它时

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

我收到错误:"' raw' RFC822有效负载消息字符串或通过/ upload / * URL上传消息"

从其他帖子看,Google似乎期待附件。 MIMEText是否有问题让它期待一个,如果有的话,我该如何解决?

2 个答案:

答案 0 :(得分:0)

list(message)不是必需的,它使API具有以下内容:

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

只需:

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

答案 1 :(得分:0)

请尝试以下操作:

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