[英]Convert message object to string (Gmail api and 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 函数中发生错误:'Message' 对象没有属性 'split'
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()
我希望这对你有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.