将邮件对象转换为字符串(Gmail api 和 python)

Convert message object to string (Gmail api and python)

我正在尝试使用 python 仅保存电子邮件的特定部分。我有变量服务、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 class 的方法 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() 

参考文献: