简体   繁体   English

如何在python中过滤gmail imap消息的日期?

[英]How to filter gmail imap messages for date in python?

I have the following code which signs into gmail via imap, selects the inbox, and searches the mailbox for emails that come from billing@gmail.com我有以下代码通过 imap 登录 gmail,选择收件箱,并在邮箱中搜索来自 billing@gmail.com 的电子邮件

How do I filter the data from gmail so that it returns only messages that have a date of today?如何过滤来自 gmail 的数据,使其仅返回日期为今天的邮件?

m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(username, password)
m.select('inbox') 
resp, data = m.search(None, '(FROM "billing@gmail.com")')
return data

I'm using the following module:我正在使用以下模块:

https://docs.python.org/2/library/imaplib.html https://docs.python.org/2/library/imaplib.html

imaplib is just a simple wrapper around the IMAP protocol which is described in this RFC , the specific part of this you would want to look at is the SEARCH command. imaplib只是本 RFC 中描述的 IMAP 协议的简单包装器,您需要查看的特定部分是 SEARCH 命令。

In answer to your question to select all messages in the current mailbox that arrived eg on 19th February 2015 you would perform the query (ON 19-Feb-2015)为了回答您选择当前邮箱中所有到达的邮件的问题,例如 2015 年 2 月 19 日,您将执行查询(ON 19-Feb-2015) 2015 年 2 月(ON 19-Feb-2015)

Some python code which will format todays date in the correct way to make the query would be:一些python代码将以正确的方式格式化今天的日期以进行查询:

import time
resp, data = m.search(None, "(ON {0})".format( time.strftime("%d-%b-%Y") ) )

now data will contain a list of message numbers recieved today.现在数据将包含今天收到的消息编号列表。

You can use SENTSINCE to get most recent messages您可以使用SENTSINCE获取最新消息

date = (datetime.date.today() - datetime.timedelta(days=2)).strftime("%d-%b-%Y")
typ, messages = m.search(None, '(ALL)', f'(SENTSINCE {date})')

To get only today messages you can use要仅获取今天的消息,您可以使用

date = datetime.date.today().strftime("%d-%b-%Y")

Une can as well replace '(ALL)' by '(UNSEEN)' to get only unseen messages Une 也可以将'(ALL)'替换为'(UNSEEN)'以只获取看不见的消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM