0

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
David
  • 1
  • 3

2 Answers2

2

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
pigrammer
  • 2,603
  • 1
  • 11
  • 24
  • 1
    This does exactly the same job.... – David Sep 24 '22 at 12:33
  • @David this retrieves all the emails from today; not from the future. This guarantees the hours will be of those you specified, because it is today. – pigrammer Sep 24 '22 at 12:36
  • For some reason it doesn't work for me, I have also noticed that when I try to print out the date each email was received e.g: msg.date I am getting wrong date – David Sep 24 '22 at 22:37
  • @David could you give us the output of `datetime.date.today()` and `datetime.datetime.utcnow().astimezone().tzinfo`? – pigrammer Sep 25 '22 at 13:50
  • >> datetime.datetime.utcnow().astimezone().tzinfo datetime.timezone(datetime.timedelta(seconds=10800), 'GTB Daylight Time') >> datetime.date.today(): datetime.date(2022, 9, 25) – David Sep 25 '22 at 18:15
0

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

Filter by time on client.

Vladimir
  • 6,162
  • 2
  • 32
  • 36