base64编码不带mime信息

base64 encoding not taking mime message

我正在尝试使用 python 发送 oauth gmail,但无法创建符合 Google 的 API 的 MimeMessages。创建示例消息后,我使用 base64 将其编码为字符串。但是,我想出了错误:TypeError: a bytes-like object is required, not 'str'

栈顶行:

return {'raw': base64.urlsafe_b64encode(message_str)}

我尝试使用不同版本的编码(encoders.encode_base64(message)message.as_string().encode("utf-8") 等)并尝试将 message.as_string() 转换为字节(如错误消息所示) 但我遇到了来自 Google 的不同错误消息,说编码不符合他们的要求,即 "MIME email messages compliant with RFC 2822 and encoded as base64url strings."

我的整个功能如下

def create_message(sender, to, subject, message_text):

    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    message_str = message.as_string()
    return {'raw': base64.urlsafe_b64encode(message_str)}

我不知道为什么这不起作用。它是从教程中复制粘贴的。我是运行python3.7.2

对于以后遇到这个问题的人来说,这似乎有效

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

根据答案 ,您可以使用:

'string'.as_bytes()

不确定为什么 gmail api docs 在他们的代码中有这个错误,但这就是我让它工作的方式。 (可能,他们指的是 python 2)


为了将这个答案放在您的具体问题的上下文中,我这样做了:

def create_message(sender, to, subject, message_text):

    message = MIMEText(message_text)
    message['To'] = to
    message['From'] = sender
    message['Subject'] = subject
    message_bytes = message.as_bytes()
    return {'raw': base64.urlsafe_b64encode(message_bytes).decode('ascii')}

I used decode('ascii') here because the result from this will need to be a json string and bytes cannot be serialized. You are likely to get an error such as TypeError: Object of type bytes is not JSON serializable otherwise.