Python imaplib search email with date and time

2024/10/2 3:21:32

I'm trying to read all emails from a particular date and time.

mail = imaplib.IMAP4_SSL(self.url, self.port)
mail.login(user, password)
mail.select(self.folder)
since = datetime.strftime(since, '%d-%b-%Y %H:%M:%S')result, data = mail.uid('search', '(SINCE "'+since+'")', 'UNSEEN')

It is working fine without time. Is it possible to search with time also?

Answer

You are not able to search by date or time, however you can retrieve a specified number of emails and filter them by date/time.

import imaplib
import email
from email.header import decode_header# account credentials
username = "[email protected]"
password = "yourpassword"# create an IMAP4 class with SSL 
imap = imaplib.IMAP4_SSL("imap.gmail.com")
# authenticate
imap.login(username, password)status, messages = imap.select("INBOX")
# number of top emails to fetch
N = 3
# total number of emails
messages = int(messages[0])for i in range(messages, messages-N, -1):# fetch the email message by IDres, msg = imap.fetch(str(i), "(RFC822)")for response in msg:if isinstance(response, tuple):# parse a bytes email into a message objectmsg = email.message_from_bytes(response[1])date = decode_header(msg["Date"])[0][0]print(date)

This example will give you the date and time for the last 3 emails in your inbox. You can adjust the number of emails fetched N if you get more than 3 emails in your specified fetch time.

This code snippet was originally written by Abdou Rockikz at thepythoncode and later modified by myself to fit your request.

Sorry I was 2 years late but I had the same question.

https://en.xdnf.cn/q/70890.html

Related Q&A

cumsum() on multi-index pandas dataframe

I have a multi-index dataframe that shows the sum of transactions on a monthly frequency. I am trying to get a cumsum() on yearly basis that respects my mapid and service multi-index. However I dont kn…

Python SSL Certification Problems in Tensorflow

Im trying to download the MNIST data which is supposedly handled in: tensorflow.examples.tutorials.mnist.input_data.read_data_sets() As far as Im aware read_data_sets sends a pull request to a server t…

How do I get a python program to run instead of opening in Notepad?

I am having some trouble with opening a .py file. I have a program that calls this .py file (i.e. pathname/example.py file.txt), but instead of running the python program, it opens it in Notepad. How t…

How to find a keys value from a list of dictionaries?

How do I get a given keys value from a list of dictionaries? mylist = [{powerpoint_color: blue,client_name: Sport Parents (Regrouped)},{sort_order: ascending,chart_layout: 1,chart_type: bar} ]The numb…

Wandering star - codeabbey task

Im trying to solve this problem and Im not sure what to do next. Link to the problem Problem statement: Suppose that some preliminary image preprocessing was already done and you have data in form of …

Find delimiter in txt to convert to csv using Python

I have to convert some txt files to csv (and make some operation during the conversion).I use csv.Sniffer() class to detect wich delimiter is used in the txt This codewith open(filename_input, r) as f1…

Assert mocked function called with json string in python

Writing some unit tests in python and using MagicMock to mock out a method that accepts a JSON string as input. In my unit test, I want to assert that it is called with given arguments, however I run i…

read certificate(.crt) and key(.key) file in python

So im using the JIRA-Python module to connect to my companys instance on JIRA and it requires me to pass the certificate and key for this. However using the OpenSSL module,im unable to read my local ce…

Admin FileField current url incorrect

In the Django admin, wherever I have a FileField, there is a "currently" box on the edit page, with a hyperlink to the current file. However, this link is appended to the current page url, an…

Difference between generator expression and generator function

Is there any difference — performance or otherwise — between generator expressions and generator functions?In [1]: def f():...: yield from range(4)...:In [2]: def g():...: return (i for i in…