【问题标题】:Fetching multiple IMAP messages at once一次获取多条 IMAP 消息
【发布时间】:2011-04-04 15:27:39
【问题描述】:

我看到的关于使用 python 通过 IMAP 加载电子邮件的示例进行搜索,然后对结果中的每个消息 ID 进行查询。我想通过一次获取它们来加快速度。

【问题讨论】:

  • 我想进行搜索,然后在一次操作中获取所有结果消息。除非有人在我不注意的时候添加了新的物理定律,否则我想我会没事的。

标签: python imap imaplib


【解决方案1】:

RFC 3501 说 fetch 需要一个序列集,但我没有看到它的定义,示例使用范围形式(2:4 = 消息 2、3 和 4)。我发现逗号分隔的 id 列表有效。在带有 imaplib 的 python 中,我有类似的东西:

    status, email_ids = con.search(None, query)
    if status != 'OK':
        raise Exception("Error running imap search for spinvox messages: "
                        "%s" % status)

    fetch_ids = ','.join(email_ids[0].split())
    status, data = con.fetch(fetch_ids, '(RFC822.HEADER BODY.PEEK[1])')
    if status != 'OK':
        raise Exception("Error running imap fetch for spinvox message: "
                        "%s" % status)
    for i in range(len(email_ids[0].split())):
        header_msg = email.message_from_string(data[i * 3 + 0][1])
        subject = header_msg['Subject'],
        date = header_msg['Date'],
        body = data[i * 3 + 1][1] # includes some mime multipart junk

【讨论】:

    【解决方案2】:

    您可以尝试使用此方法在 1 次转到服务器中获取所有邮件的标头信息。

    import imaplib
    import email
    
    obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
    obj.login('username', 'password')
    obj.select('folder_name')
    resp,data = obj.uid('FETCH', '1:*' , '(RFC822.HEADER)')
    messages = [data[i][1].strip() + "\r\nSize:" + data[i][0].split()[4] + "\r\nUID:" + data[i][0].split()[2]  for i in xrange(0, len(data), 2)]
    for msg in messages:
        msg_str = email.message_from_string(msg)
        message_id = msg_str.get('Message-ID')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 2012-01-09
      • 2017-01-24
      • 2020-02-24
      • 2014-07-18
      • 2016-05-08
      • 1970-01-01
      相关资源
      最近更新 更多