【问题标题】:Get all the mail with body using imap in python在 python 中使用 imap 获取所有带有正文的邮件
【发布时间】:2015-03-24 18:02:31
【问题描述】:

我是 python 新手,想获取所有带有 gmail 帐户正文的邮件,但我只能获取最旧的电子邮件。 我的代码如下,提前感谢您的帮助。

#!/usr/bin/env python


import getpass
import imaplib
import email
from email.parser import HeaderParser

M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
add = raw_input("Email address: ")
password = getpass.getpass()
M.login(add, password)

M.select()
resp, data = M.FETCH(1, '(RFC822)')
mail = email.message_from_string(data[0][1])

for part in mail.walk():
  # multipart are just containers, so we skip them
  if part.get_content_maintype() == 'multipart':
      continue

  # we are interested only in the simple text messages
  if part.get_content_subtype() != 'plain':
    continue

  payload = part.get_payload()
  print payload

【问题讨论】:

  • 我们在谈论多少条消息?这可以改变实施。您正在使用 m.fetch(1, ...) 来获取第一条消息正文。更改第一个参数以适应。您可以使用循环并获取帐户中的所有消息。注意:imaplib 级别很低。如果您不了解 IMAP,则很难使用。

标签: python-2.7 gmail imap


【解决方案1】:

我更喜欢使用 uid 进行迭代,因为它们是独一无二的,所以这是我的代码:

imap.select('INBOX',False)
typ, ids = imap.uid('search',None,'ALL')
ids = ids[0].decode().split()
for id in ids:
    typ, messageRaw = imap.uid('fetch',id,'(RFC822)')
    message = email.message_from_bytes(messageRaw[0][1])
    for part in message.walk():

【讨论】:

    【解决方案2】:

    你可以试试高级库 - https://github.com/ikvk/imap_tools

    # get list of email body from INBOX folder
    with MailBox('imap.mail.com').login('test@mail.com', 'password') as mailbox:
        body_set = [msg.body for msg in mailbox.fetch()]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-16
      • 2013-04-30
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多