Quantcast
Channel: Active questions tagged email - Stack Overflow
Viewing all articles
Browse latest Browse all 29947

Python IMAP email for the last 24 hours

$
0
0

I am trying to fetch emails for the last 24 hours using IMAP.This is my code

import imaplib, email, os
import datetime as dt
date_time = dt.datetime.now()
user = "email"
password = "password"
imap_url = "imap.gmail.com"
connection = imaplib.IMAP4_SSL(imap_url)
connection.login(user, password)
connection.select()
result, data = connection.uid('search', None, "ALL")
#This is set to one minute ago; you can change timedelta's argument to whatever you want it to be
last30MinuteDateTime = dt.datetime.now() - dt.timedelta(minutes = 60 )
if result == 'OK':
    for num in data[0].split():
        result, data = connection.uid('fetch', num, '(RFC822)')
        if result == 'OK':
            email_message = email.message_from_bytes(data[0][1])
            print('From:' + email_message['From'])
            print('To:' + email_message['To'])
            print('Date:' + email_message['Date'])
            print('Subject:' + str(email_message['Subject']))
            print('Content:' + str(email_message.get_payload()[0]))
connection.close()
connection.logout()  

as you can see my code return all emails.My questions is how do i get only the emails from the last 24 hours. thanks


Viewing all articles
Browse latest Browse all 29947

Latest Images

Trending Articles



Latest Images