Search code examples
pythonemailpython-3.ximapgmail-imap

Python IMAP - Read Gmail with '+' in email address


I've previously used imaplib in Python 3to extract emails from gmail. However I would want to generate a script to differentiate emails to the same address with different strings after a plus sign. For example, the base email address can be:

[email protected]

Then I would want to separately read all emails with the addresses:

[email protected],
[email protected],
[email protected].

Therefore I would wind up with a dictionary of lists containing the specific emails. This only works for [email protected]. For example:

{'example':[],
 'example_test':[],
 'example_test2':[]}

Currently I can retrieve the emails that I need with this function from a class:

def get_emails(self):
    """Retrieve emails"""
    self.M = imaplib.IMAP4_SSL(self.server)
    self.M.login(self.emailaddress,self.password)
    self.M.select(readonly=1)
    self.M.select('INBOX', readonly=True)
    #Yesterdays date
    date = (datetime.date.today() - datetime.timedelta(self.daysback)).strftime("%d-%b-%Y")
    print("Selecting email messages since %s" % date)
    #Retrieve all emails from yesterday on
    result,data = self.M.uid('search', None, '(SENTSINCE {date})'.format(date=date))
    return result,data

Solution

  • You should directly use the exact mail address you want in the IMAP search request. For example it could be something like :

    result,data = self.M.uid('search', None, '(SENTSINCE {date})'.format(date=date),
        ('TO [email protected]'))