我是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
答案 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()]