如何解决“需要一个类似字节的对象,而不是'str'".在create_message()函数中? [英] How to solve "a bytes-like object is required, not 'str'" in create_message() function?

查看:70
本文介绍了如何解决“需要一个类似字节的对象,而不是'str'".在create_message()函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用create_message()创建新消息时出现错误. https://developers.google.com/gmail/api/guides/drafts上列出的函数.

I'm getting an error in creating a new message using create_message(). function listed over https://developers.google.com/gmail/api/guides/drafts.

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

错误:TypeError:需要一个类似字节的对象,而不是'str'

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

推荐答案

base64.urlsafe_b64encode 预期为 bytes ,但是 message.as_string()的类型为 str .

base64.urlsafe_b64encode expects bytes, but the type of message.as_string() is str.

使用邮件的 as_bytes 方法代替.

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

这篇关于如何解决“需要一个类似字节的对象,而不是'str'".在create_message()函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆