我希望使用IMAP从电子邮件帐户收件箱中返回n个(最有可能是10个)最近的电子邮件。
到目前为止,我拼凑了一起:
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']
这回复电子邮件标题很好,但它似乎是一个半随机的电子邮件集合,而不是最近的10个。
如果有帮助,我将连接到Exchange 2010服务器。其他方法也欢迎,IMAP似乎是最合适的,因为我只想阅读不发送的电子邮件。
答案 0 :(得分:11)
sort命令可用,但不保证IMAP服务器支持它。例如,Gmail不支持SORT命令。
要尝试sort命令,您可以替换:
M.search(None, 'ALL')
与
M.sort(search_critera, 'UTF-8', 'ALL')
然后search_criteria
将是一个字符串,如:
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
根据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的世界疯狂而疯狂。祝你好运
答案 1 :(得分:1)
这是获取emailFrom,emailSubject,emailDate,emailContent等的代码。
import imaplib, email, os
user = "your@email.com"
password = "pass"
imap_url = "imap.gmail.com"
connection = imaplib.IMAP4_SSL(imap_url)
connection.login(user, password)
result, data = connection.uid('search', None, "ALL")
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()
答案 2 :(得分:0)
这对我有用〜
import imaplib
from email.parser import HeaderParser
M = imaplib.IMAP4_SSL('my.server')
user = 'username'
password = 'password'
M.login(user, password)
(retcode, messages) =M.search(None, 'ALL')
news_mail = get_mostnew_email(messages)
for i in news_mail :
data = M.fetch(i, '(BODY[HEADER])')
header_data = data[1][0][1]
parser = HeaderParser()
msg = parser.parsestr(header_data)
print msg['subject']
这是获得更新的电子邮件功能:
def get_mostnew_email(messages):
"""
Getting in most recent emails using IMAP and Python
:param messages:
:return:
"""
ids = messages[0] # data is a list.
id_list = ids.split() # ids is a space separated string
#latest_ten_email_id = id_list # get all
latest_ten_email_id = id_list[-10:] # get the latest 10
keys = map(int, latest_ten_email_id)
news_keys = sorted(keys, reverse=True)
str_keys = [str(e) for e in news_keys]
return str_keys
答案 3 :(得分:0)
# get recent one email
from imap_tools import MailBox
with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
for message in mailbox.fetch(limit=1, reverse=True):
print(msg.date_str, msg.subject)
答案 4 :(得分:0)
Gmail的解决方法。由于IMAP.sort('DATE','UTF-8','ALL')不适用于gmail,因此我们可以将值和日期插入列表,然后以相反的日期顺序对列表进行排序。可以使用计数器检查前n个邮件。如果有数百封邮件,则此方法将花费几分钟。
M.login(user,password)
rv,data= M.search(None,'ALL')
if rv=='OK':
msg_list=[]
for num in date[0].split():
rv,data=M.fetch(num,'(RFC822)')
if rv=='OK':
msg_object={}
msg_object_copy={}
msg=email.message_from_bytes(data[0][1])
msg_date=""
for val in msg['Date'].split(' '):
if(len(val)==1):
val="0"+val
# to pad the single date with 0
msg_date=msg_date+val+" "
msg_date=msg_date[:-1]
# to remove the last space
msg_object['date']= datetime.datetime.strptime(msg_date,"%a, %d %b %Y %H:%M:%S %z")
# to convert string to date time object for sorting the list
msg_object['msg']=msg
msg_object_copy=msg_object.copy()
msg_list.append(msg_object_copy)
msg_list.sort(reverse=True,key=lambda r:r['date'])
# sorts by datetime so latest mails are parsed first
count=0
for msg_obj in msg_list:
count=count+1
if count==n:
break
msg=msg_obj['msg']
# do things with the message