Get emails with imap_tools with python

2.5k Views Asked by At

I want to receive all the today's email texts from a specific sender and put them into a list from outlook with imap-tools

I have made the following function but the problem is that it doesn't retrieve emails from 12:00AM - 12:00PM, is there any way to specify the hours for getting the proper messages?

def get_emails(username, password, sender):
    from imap_tools import MailBox, A

    emails = []

    with MailBox('outlook.office365.com').login(username, password, 'INBOX') as mailbox:
        for msg in mailbox.fetch(
                A(
                    A(date_gte=datetime.date.today()),  # get the today's emails
                    A(from_=sender),         # from the specific senderEmailAddress
                ),
                mark_seen = True
            ):
            if msg.subject == "Subject":
                emails.append(msg.text)
        return emails
2

There are 2 best solutions below

5
pigrammer On

Use date (imap_tools documentation):

from imap_tools import MailBox, A

def get_emails(username, password, sender):
    emails = []

    with MailBox('outlook.office365.com').login(login_name, login_password, 'INBOX') as mailbox:
        for msg in mailbox.fetch(
                A(date=datetime.date.today(), from_=sender),
                mark_seen = True
            ):
            if msg.subject == "Subject":
                emails.append(msg.text)
        return email
0
Vladimir On

There is no filter by time in IMAP, only by date.

Filter by time on client.