【问题标题】:How can I read the mail body of a mail with Python?如何使用 Python 读取邮件的邮件正文?
【发布时间】:2021-01-30 06:47:55
【问题描述】:

登录并阅读主题作品。读取正文时发生错误。错误是什么?在互联网上,错误总是在这部分:“email.message_from_bytes(data[0][1].decode())”但我认为这部分是正确的。

# Connection settings
        HOST = 'imap.host'
        USERNAME = 'name@domain.com'
        PASSWORD = 'password'

        m = imaplib.IMAP4_SSL(HOST, 993)
        m.login(USERNAME, PASSWORD)
        m.select('INBOX')

        result, data = m.uid('search', None, "UNSEEN")
        if result == 'OK':
              for num in data[0].split()[:5]:
                    result, data = m.uid('fetch', num, '(RFC822)')
                    if result == 'OK':
                          email_message_raw = email.message_from_bytes(data[0][1])
                          email_from = str(make_header(decode_header(email_message_raw['From'])))
                          # von Edward Chapman -> https://stackoverflow.com/questions/7314942/python-imaplib-to-get-gmail-inbox-subjects-titles-and-sender-name
                          subject = str(email.header.make_header(email.header.decode_header(email_message_raw['Subject'])))
                          # content = email_message_raw.get_payload(decode=True)
                          # von Todor Minakov -> https://stackoverflow.com/questions/17874360/python-how-to-parse-the-body-from-a-raw-email-given-that-raw-email-does-not
                          b = email.message_from_string(email_message_raw)
                          body = ""

                          if b.is_multipart():
                              for part in b.walk():
                                  ctype = part.get_content_type()
                                  cdispo = str(part.get('Content-Disposition'))

                                  # skip any text/plain (txt) attachments
                                  if ctype == 'text/plain' and 'attachment' not in cdispo:
                                      body = part.get_payload(decode=True)  # decode
                                      break
                          # not multipart - i.e. plain text, no attachments, keeping fingers crossed
                          else:
                              body = b.get_payload(decode=True)
                          
        m.close()
        m.logout()


        txt = body
        regarding = subject
        print("###########################################################")
        print(regarding)
        print("###########################################################")
        print(txt)
        print("###########################################################")

错误信息:

TypeError: initial_value 必须是 str 或 None,而不是 Message

感谢cmets的回复

【问题讨论】:

  • 请发布堆栈跟踪
  • 给定email_message_raw = email.message_from_bytes(data[0][1])email_message_raw 是一个消息对象,然后您尝试在调用b = email.message_from_string(email_message_raw) 时使用它,这需要一个搅拌。
  • 我现在该怎么办?

标签: python python-3.x imap


【解决方案1】:
from imap_tools import MailBox, AND

# get email bodies from INBOX 
with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
    for msg in mailbox.fetch():
        body = msg.text or msg.html
    

https://github.com/ikvk/imap_tools

【讨论】:

    【解决方案2】:

    一切就绪。只需了解一些概念即可。

    “email”库允许您使用其解析器 API(例如 message_from_bytes()、message_from_string() 等)将典型的电子邮件字节转换为易于使用的名为 Message 的对象。

    典型的错误是由于输入错误。

    email.message_from_bytes(data[0][1].decode())

    上面的函数 message_from_bytes 将字节作为输入而不是 str。因此,解码 data[0][1] 并通过解析器 API 输入是多余的。

    简而言之,您尝试使用 message_from_bytes(data[0][1]) 和 message_from_string(email_message_raw) 两次解析原始电子邮件。摆脱其中一个,你就万事大吉了!

    试试这个方法:

        HOST = 'imap.host'
        USERNAME = 'name@domain.com'
        PASSWORD = 'password'
    
        m = imaplib.IMAP4_SSL(HOST, 993)
        m.login(USERNAME, PASSWORD)
        m.select('INBOX')
    
        result, data = m.uid('search', None, "UNSEEN")
        if result == 'OK':
              for num in data[0].split()[:5]:
                    result, data = m.uid('fetch', num, '(RFC822)')
                    if result == 'OK':
                          email_message = email.message_from_bytes(data[0][1])
                          email_from = str(make_header(decode_header(email_message_raw['From'])))
                          # von Edward Chapman -> https://stackoverflow.com/questions/7314942/python-imaplib-to-get-gmail-inbox-subjects-titles-and-sender-name
                          subject = str(email.header.make_header(email.header.decode_header(email_message_raw['Subject'])))
                          # content = email_message_raw.get_payload(decode=True)
                          # von Todor Minakov -> https://stackoverflow.com/questions/17874360/python-how-to-parse-the-body-from-a-raw-email-given-that-raw-email-does-not
                          # b = email.message_from_string(email_message_raw)
                          # this is already set as Message object which have many methods (i.e. is_multipart(), walk(), etc.)
                          b = email_message 
                          body = ""
    
                          if b.is_multipart():
                              for part in b.walk():
                                  ctype = part.get_content_type()
                                  cdispo = str(part.get('Content-Disposition'))
    
                                  # skip any text/plain (txt) attachments
                                  if ctype == 'text/plain' and 'attachment' not in cdispo:
                                      body = part.get_payload(decode=True)  # decode
                                      break
                          # not multipart - i.e. plain text, no attachments, keeping fingers crossed
                          else:
                              body = b.get_payload(decode=True)
                          
        m.close()
        m.logout()
    
    
        txt = body
        regarding = subject
        print("###########################################################")
        print(regarding)
        print("###########################################################")
        print(txt)
        print("###########################################################")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-23
      • 2012-06-29
      • 2014-07-27
      • 2022-06-13
      • 2012-02-15
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多