【问题标题】:Python imaplib search email with date and timePython imaplib 使用日期和时间搜索电子邮件
【发布时间】:2019-02-02 20:53:27
【问题描述】:

我正在尝试阅读特定日期和时间的所有电子邮件。

mail = imaplib.IMAP4_SSL(self.url, self.port)
mail.login(user, password)
mail.select(self.folder)
since = datetime.strftime(since, '%d-%b-%Y %H:%M:%S')

result, data = mail.uid('search', '(SINCE "'+since+'")', 'UNSEEN')

它没有时间就可以正常工作。也可以按时间搜索吗?

【问题讨论】:

    标签: python python-3.x python-2.7 imaplib


    【解决方案1】:

    很遗憾没有。 RFC 3501 §6.4.4 中定义的通用 IMAP 搜索语言不包括任何按时间搜索的规定。

    SINCE 被定义为采用 <date> 项目,该项目又被定义为 date-day "-" date-month "-" date-year,带或不带引号。

    IMAP 甚至不知道时区,因此您必须根据 INTERNALDATE 项在本地过滤掉不适合您范围的前几条消息。您甚至可能需要多获取几天的消息。

    如果您使用的是 Gmail,则可以使用 Gmail 搜索语言,该语言以 extension 的形式提供。

    【讨论】:

      【解决方案2】:

      您无法按日期或时间搜索,但您可以检索指定数量的电子邮件并按日期/时间过滤它们。

      import imaplib
      import email
      from email.header import decode_header
      
      # account credentials
      username = "youremailaddress@provider.com"
      password = "yourpassword"
      
      # create an IMAP4 class with SSL 
      imap = imaplib.IMAP4_SSL("imap.gmail.com")
      # authenticate
      imap.login(username, password)
      
      status, messages = imap.select("INBOX")
      # number of top emails to fetch
      N = 3
      # total number of emails
      messages = int(messages[0])
      
      for i in range(messages, messages-N, -1):
          # fetch the email message by ID
          res, msg = imap.fetch(str(i), "(RFC822)")
          for response in msg:
              if isinstance(response, tuple):
                  # parse a bytes email into a message object
                  msg = email.message_from_bytes(response[1])
                  date = decode_header(msg["Date"])[0][0]
                  print(date)
      

      此示例将为您提供收件箱中最后 3 封电子邮件的日期和时间。如果您在指定的提取时间内收到超过 3 封电子邮件,您可以调整提取的电子邮件数量N

      此代码 sn-p 最初由 Abdou Rockikz 在 thepythoncode 编写,后来我自己修改以满足您的要求。

      对不起,我迟到了 2 年,但我有同样的问题。

      【讨论】:

        猜你喜欢
        • 2017-04-04
        • 1970-01-01
        • 1970-01-01
        • 2011-09-26
        • 1970-01-01
        • 2019-06-03
        • 2011-04-01
        • 2012-11-20
        • 1970-01-01
        相关资源
        最近更新 更多