我是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
我更喜欢使用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():
您可以尝试高级库-https://github.com/ikvk/imap_tools
# get list of email body from INBOX folder
with MailBox('imap.mail.com').login('[email protected]', 'password') as mailbox:
body_set = [msg.body for msg in mailbox.fetch()]