【问题标题】:How to get only subject,from and body of email using imaplib and python3如何使用 imaplib 和 python3 仅获取电子邮件的主题、来自和正文
【发布时间】:2021-07-29 19:38:18
【问题描述】:

我想使用电子邮件的 message_numbers 从电子邮件的主题和正文中获取。 我不想要任何附件或图像。只是正文的纯文本。 有人可以帮我一些代码sn-p吗?我被困在这一点上。

这是我用来获取数据的当前代码 sn-p:

import imaplib
import config
import bs4
import email

imap = imaplib.IMAP4_SSL(config.imap_server,config.imap_port)
r, d = imap.login(config.username, config.password)
imap.select("Inbox")
r, d = imap.uid('search', None, "ALL")
message_numbers = d[0].decode('utf8').split(' ')
for msg_uid in message_numbers:
    r, d = imap.uid('FETCH', msg_uid, '(RFC822)')
    try:
        raw_email = d[0][1].decode('utf8')
    except:
        raw_email = str(bs4.BeautifulSoup(d[0][1],'lxml'))
    email_message = email.message_from_string(raw_email)
    print(email_message) # here i need only subject,from and body in string format and i dont want attachments

【问题讨论】:

    标签: python python-3.x imap


    【解决方案1】:

    您的代码实现了几个不正确的假设。

    您不能假设 IMAP 消息是 UTF-8 格式的。事实上,很可能不是。

    您不能假设电子邮件正文是 HTML。再次,机会是,它不是。无论如何,使用 BeautifulSoup 和 LXML 来分​​离电子邮件消息本身是相当疯狂的;使用 email 解析器,而不是 XML 解析器。 Python 内置了一个。

    Python email 库有一个旧版本仍然受支持,但是 3.6+ 中的新版本有一个你肯定想要的功能 - 当有多个时,它可以尝试猜测你所说的“主体”是什么意思部分。当然,这只是一种启发式方法; “正文”在多部分消息中没有明确定义。或许也可以看看What are the "parts" in a multipart email?

    IMAP FETCH 命令会将邮件标记为“已看到”;也许您想在选择收件箱时使用readonly=True?另见Fetch an email with imaplib but do not mark it as SEEN

    import imaplib
    import config
    # import bs4     # not used
    import email
    from email.policy import default  # for Python 3.6+ EmailMessage support
    
    # Use a context manager
    with imaplib.IMAP4_SSL(config.imap_server,config.imap_port) as imap:
        r, d = imap.login(config.username, config.password)
        imap.select("Inbox", readonly=True)
        r, d = imap.uid('search', None, "ALL")
        message_numbers = d[0].decode('utf8').split(' ')
        for msg_uid in message_numbers:
            r, d = imap.uid('FETCH', msg_uid, '(RFC822)')
            message = email.message_from_bytes(d[0][1], policy=default)
            print("from:", message['from'])
            print("subject:", message['subject'])
            # Guess at "the" body part
            # Maybe parse this like before if it is an HTML part?
            print(message.get_body().get_content())
            print()
    

    【讨论】:

      【解决方案2】:
      from imap_tools import MailBox, A
      with MailBox('imap.mail.com').login('test@mail.com', 'pwd', 'INBOX') as mailbox:
          for msg in mailbox.fetch(A(all=True)):
              print(msg.subject)
              print(msg.from_)
              print(msg.text or msg.html)
      

      https://github.com/ikvk/imap_tools

      问候,imap_tools 作者。

      【讨论】:

        猜你喜欢
        • 2011-09-06
        • 2015-04-17
        • 2014-10-03
        • 2015-04-29
        • 2011-01-14
        • 2012-12-11
        • 2012-10-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多