1

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
Juzar
  • 13
  • 1
  • 7
  • How many messages are we talking about? That can change the implementation. You are using m.fetch(1, ...) to fetch the first messages body. Change the first parameter to suit. You can use a loop and fetch all the messages in the account. Be careful: imaplib is very low level. It is difficult to use if you do not understand IMAP. – Max Mar 24 '15 at 21:58

2 Answers2

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

You can try high level library - 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()]
Vladimir
  • 6,162
  • 2
  • 32
  • 36