Get all the mail with body using imap in python

吃可爱长大的小学妹 提交于 2019-12-08 06:02:08

问题


I am new to python and want to get all the mails with the body in the gmail account , but i am able to get only the oldest email. My code is given below , thanks for help in advance.

#!/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

回答1:


i prefer to use uids for iterating, because they are unique, so that's my code:

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://stackoverflow.com/questions/29239777/get-all-the-mail-with-body-using-imap-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!