0

我正在尝试使用 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 函数中发生错误:“消息”对象没有属性“拆分”

4

1 回答 1

2

回答:

get_payload()该类不存在该方法email.message。你需要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() 

参考:

于 2020-08-25T12:29:20.513 回答