如何解决将消息对象转换为字符串Gmail api和python 答案:代码修复:参考文献:
我正在尝试使用python仅保存电子邮件的特定部分。我有变量service,userId和msg_id,但我不知道如何将变量plainText转换为字符串,以便在get_info函数中获得所需的部分
def get_message(service,user_id,msg_id):
try:
#get the message in raw format
message = service.users().messages().get(userId=user_id,id=msg_id,format='raw').execute()
#encode the message in ASCII format
msg_str = base64.urlsafe_b64decode(message['raw'].encode("ASCII")).decode("ASCII")
#put it in an email object
mime_msg = email.message_from_string(msg_str)
#get the plain and html text from the payload
plainText,htmlText = mime_msg.get_payload()
print(get_info(plainText,"start","finish"))
except Exception as error:
print('An error occurred in the get_message function: %s' % error)
def get_info(plainText,start,end):
usefullText = plainText.split(start)[2]
usefullText = usefullText.split(end)[0]
return usefullText
运行代码后,我收到以下错误消息:
get_message函数中发生错误:“消息”对象没有属性“分裂”
解决方法
答案:
对于email.message
类而言,方法get_payload()
不存在。您需要改用as_string()
。
代码修复:
try
块中的代码需要从以下位置进行更新:
#get the plain and html text from the payload
plainText,htmlText = mime_msg.get_payload()
收件人:
#get the plain and html text from the payload
plainText,htmlText = mime_msg.as_string()
我希望这对您有帮助!
参考文献:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。