如何阅读带有 Python 的邮件的邮件正文?

How can I read the mail body of a mail with Python?

登录并阅读主题作品。读取正文时发生错误。错误是什么?在互联网上,错误总是在这部分:“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 -> 
                          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 -> 
                          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 must be str or None, not Message

感谢评论和回复

你已经准备好了一切。只需要了解几个概念。

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

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

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

上面的函数 message_from_bytes 将 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 -> 
                      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 -> 
                      # 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("###########################################################")
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