imaplib

Fetching all senders' emails in imaplib


With this I get a list of email from particular senders:

import email
import imaplib
username = "TBD"
pw = "TBD"
suka = imaplib.IMAP4_SSL("imap.gmail.com")
suka.login(username, pw)
suka.select("INBOX")
key = 'FROM'
value = 'TBD' 
_, data = suka.search(None, key, value)
mail_id_list = data[0].split()
msgs = [] 

But what if need to skip giving a sender "FROM", but want to get a list of just all messages in the inbox. Something like: key = 'FROM' value = any. I don't see such possibility in the lib docs, but suppose such a function should exist. Many thanks for any help.


Solution

  • You can simply use:

    _, data = suka.search(None, "ALL")
    

    Your full code will look like this:

    import email
    import imaplib
    username = "TBD"
    pw = "TBD"
    suka = imaplib.IMAP4_SSL("imap.gmail.com")
    suka.login(username, pw)
    suka.select("INBOX")
    _, data = suka.search(None, "ALL")
    mail_id_list = data[0].split()
    msgs = []
    

    Updated

    username = "TBD"
    pw = "TBD"
    suka = imaplib.IMAP4_SSL("imap.gmail.com")
    suka.login(username, pw)
    suka.select("INBOX")
    
    # Search for all messages in the inbox
    _, data = suka.search(None, "ALL")
    mail_id_list = data[0].split()
    
    # Loop through the message IDs and retrieve the message contents
    for mail_id in mail_id_list:
        _, message_data = suka.fetch(mail_id, "(RFC822)")
        message = email.message_from_bytes(message_data[0][1])
        msgs.append(message)