使用IMAP和Python获取最近的电子邮件 [英] Getting n most recent emails using IMAP and Python
问题描述
我正在寻找通过IMAP从电子邮件帐户收件箱返回最近的n个(最有可能10个)电子邮件。
到目前为止,我已经拼凑在一起了:
import imaplib
from email.parser import HeaderParser
M = imaplib.IMAP4_SSL 'my.server')
user ='username'
password ='password'
M.login(用户,密码)
M.search(无,'ALL')
for i in range(1,10):
data = M.fetch(i,'(BODY [HEADER])')
header_data = data [1] [0] [1 ]
parser = HeaderParser()
msg = parser.parsestr(header_data)
打印msg ['subject']
这是返回电子邮件标题,但它似乎是一个半随机的电子邮件收集,而不是最近的10个。
如果有帮助,我正在连接到Exchange 2010服务器。其他方法也受欢迎,IMAP似乎是最合适的,因为我只想阅读电子邮件不发送任何。
sort命令可用,但不能保证IMAP服务器支持。例如,Gmail不支持SORT命令。
要尝试排序命令,您将替换:
M.search(无,'ALL')
with
M.sort(search_critera,'UTF-8','ALL')
/ p>
然后 search_criteria
将是一个字符串,如:
search_criteria ='DATE'#取消,最近的电子邮件最后
search_criteria ='REVERSE DATE'#Descending,最新的电子邮件首先
search_criteria ='[ REVERSE] sort-key'#format进行排序
根据 RFC5256 这些都是有效的 sort-key
的:
ARRIVAL/CC/DATE/FROM/SIZE/SUBJECT/TO
注意:
1.需要charset,尝试 US-ASCII
或 UTF- 8
所有其他人不需要IMAP服务器支持
2.还需要搜索critera。 ALL
命令是有效的,但有很多。请参阅 http://www.networksorcery.com/enp/rfc/rfc3501.txt
IMAP的世界是疯狂而疯狂的。祝你好运
I'm looking to return the n (most likely 10) most recent emails from an email accounts inbox using IMAP.
So far I've cobbled together:
import imaplib
from email.parser import HeaderParser
M = imaplib.IMAP4_SSL('my.server')
user = 'username'
password = 'password'
M.login(user, password)
M.search(None, 'ALL')
for i in range (1,10):
data = M.fetch(i, '(BODY[HEADER])')
header_data = data[1][0][1]
parser = HeaderParser()
msg = parser.parsestr(header_data)
print msg['subject']
This is returning email headers fine, but it seems to be a semi-random collection of emails that it gets, not the 10 most recent.
If it helps, I'm connecting to an Exchange 2010 server. Other approaches also welcome, IMAP just seemed the most appropriate given that I only wanted to read the emails not send any.
The sort command is available, but it is not guaranteed to be supported by the IMAP server. For example, Gmail does not support the SORT command.
To try the sort command, you would replace:
M.search(None, 'ALL')
with
M.sort(search_critera, 'UTF-8', 'ALL')
Then search_criteria
would be a string like:
search_criteria = 'DATE' #Ascending, most recent email last
search_criteria = 'REVERSE DATE' #Descending, most recent email first
search_criteria = '[REVERSE] sort-key' #format for sorting
According to RFC5256 these are valid sort-key
's:
"ARRIVAL" / "CC" / "DATE" / "FROM" / "SIZE" / "SUBJECT" / "TO"
Notes:
1. charset is required, try US-ASCII
or UTF-8
all others are not required to be supported by the IMAP server
2. search critera is also required. The ALL
command is a valid one, but there are many. See more at http://www.networksorcery.com/enp/rfc/rfc3501.txt
The world of IMAP is wild and crazy. Good luck
这篇关于使用IMAP和Python获取最近的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!