3

I'm using the following code to download all my emails from gmail, but unfortunately, the total number of emails returned does not match the total number of emails in the account. In particular, I'm able to get the first 43 messages, but I count 20+ more in the inbox that are missed. Perhaps this is some sort of limit on the number that can be pulled back(?). Thanks in advance for any assistance provided!

import imaplib, email, base64

def fetch_messages(username, password):
    messages = []
    conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    conn.login(username, password)
    conn.select()
    typ, data = conn.uid('search', None, 'ALL')

    for num in data[0].split():
        typ, msg_data = conn.uid('fetch', num, '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                messages.append(email.message_from_string(response_part[1]))
        typ, response = conn.store(num, '+FLAGS', r'(\Seen)')
    return messages
3
  • Have you tried conn.search(None, 'ALL') to get all the messages? Commented Feb 25, 2013 at 21:00
  • yes, i updated the code snippet to make it clear that 'status' was set to 'ALL' Commented Feb 25, 2013 at 21:03
  • You might try using conn.search() instead of conn.uid(). You'll get indices rather than uids, but you can get the uid when you fetch the message. Commented Feb 25, 2013 at 21:15

1 Answer 1

1

I use the following to get all email messages.

resp,data = mail.uid('FETCH', '1:*' , '(RFC822)')

and to get all the ids I use:

result, data = mail.uid('search', None, "ALL")
print data[0].split()

gives:

['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', ... etc ]

EDIT

In my case the follow returns 202 dates which is in excess of what the OP is looking for and is the correct number.

resp,data = mail.uid('FETCH', '1:*' , '(RFC822)')
messages = [data[i][1].strip() for i in xrange(0, len(data), 2)] 
for msg in messages:
    msg_str = email.message_from_string(msg)
    print msg_str.get('Date')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.