【问题标题】:Extract first line of email body using python使用python提取电子邮件正文的第一行
【发布时间】:2015-12-13 14:42:38
【问题描述】:

我可以使用 python(imap 和邮件模块)打开电子邮件,主要遵循这里的建议:How can I get an email message's text content using python?

但我只需要打印每封电子邮件正文的第一行 - 我该怎么做?

    for part in email_message.walk():
    # each part is a either non-multipart, or another multipart message
    # that contains further parts... Message is organized like a tree
    if part.get_content_type() == 'text/plain':
        print part.get_payload() # prints the raw text

这是我目前必须打印的正文,有什么想法可以将其限制在电子邮件的第一行吗?

【问题讨论】:

    标签: python email gmail imap


    【解决方案1】:

    字符串库中有一个专门用于此操作的方法 - splitlines(),它负责处理不同的行尾(\n 或 \r\n)。 From the doc:

    例如,'ab c\n\nde fg\rkl\r\n'.splitlines() 返回 ['ab c', '', 'de fg', 'kl'],

    因为它返回一个数组,所以获取第一个元素是微不足道的 - [0]。如果最后一个元素以换行符结尾,它也不会返回额外的空字符串,这与 split('n') 不同。

    另外,您最好使用get_payload(decode=True),它会为您处理 base64 等解码。最后,这是您更新的示例:

    for part in email_message.walk():
    # each part is a either non-multipart, or another multipart message
    # that contains further parts... Message is organized like a tree
    if part.get_content_type() == 'text/plain':
        # you may want to break it out in 2 statements for readability
        print part.get_payload(decode=True).splitlines()[0] # prints the first line
    

    顺便说一句,文本附件也是“文本/纯文本”内容类型,可能会弄乱您的预期数据;你可能想跳过那些 - see my post here(自我引用,xaxax)。

    HTH

    【讨论】:

      【解决方案2】:

      根据文档 get_payload() 应该返回一个字符串,所以这应该可以工作。

      for part in email_message.walk():
          # each part is a either non-multipart, or another multipart message
          # that contains further parts... Message is organized like a tree
          if part.get_content_type() == 'text/plain':
              lines=part.get_payload().split("\n")
              print lines[0]
      

      【讨论】:

        猜你喜欢
        • 2019-04-12
        • 1970-01-01
        • 2016-01-11
        • 1970-01-01
        • 2019-01-09
        • 2013-04-30
        • 2018-10-05
        • 1970-01-01
        • 2018-11-10
        相关资源
        最近更新 更多