使用python中的imap获取身体的所有邮件

时间:2015-03-24 18:02:32

标签: python-2.7 gmail imap

我是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

2 个答案:

答案 0 :(得分:0)

我更喜欢使用uids进行迭代,因为它们是唯一的,所以这是我的代码:

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():

答案 1 :(得分:0)

您可以尝试高级图书馆-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()]