Python imaplib Search using senders domain

2019-06-10 09:25发布

问题:

I am trying to search using the IMAP search function to only return users that have sent emails from a specific domain. I am hoping this is actually possible.

For example let's say I want to only fetch emails from users sending from addresses coming from @stackoverflow.com.

We connect, login etcetera then search as below.

c = imaplib.IMAP4(imapserver)    
c.starttls() 
c.login(username, password)    
c.list()    
c.select('INBOX')
c.search(None, 'UNSEEN FROM "@stackoverflow.com"') 

However this returns no results. When I search for the user by part of their name e.g.

c.search(None, 'UNSEEN FROM "John"')

it works even if the part is nothing like their username e.g. j.smith@stackoverflow.com.

As I only want to fetch those that are to be automatically handled from these specific domains and leave the rest unread I am hoping there is something else I can do.

回答1:

Just needed to delve a little bit further into what was happening

c.search(None, 'UNSEEN HEADER FROM "stackoverflow.com"')

Will get all unread emails coming from an email address from the 'stackoverflow.com' domain.