【问题标题】:Convert message object to string (Gmail api and python)将消息对象转换为字符串(Gmail api 和 python)
【发布时间】:2020-12-13 02:01:10
【问题描述】:

我正在尝试使用 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_from_string(msg_str)的位置,但很可能mime_msg.get_payload()不会检索纯文本而是对象消息
  • 我添加了这两个导入:import email import base64
  • 您可以查看print( type(plainText) ) 以查看您拥有的对象类型 - 然后您可以找到文档并阅读有关其方法和属性的更多信息。您还可以使用print( dir(plainText) ) 查看哪些方法具有此对象 - 也许有plainText.textplainText.body 或类似的东西可以从消息中获取原始文本。你也可以试试help(plainText)。如果您使用一些IDE(如PyCharm),那么您可以尝试plainText.(在末尾带有点)并按Ctrl+Space 来获取有关此对象中方法的信息。
  • 如果是email Message,那么在文档中你可以看到它有as_string()get_body()等。它也有__str__(),所以你可以使用str(plainText),但这可能会给你用所有元素串起来——标题、正文、附件。
  • 尝试plainText.get_content() 以字符串形式获取邮件正文。

标签: python gmail-api tostring


【解决方案1】:

答案:

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() 

参考资料:

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 2014-09-07
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    相关资源
    最近更新 更多