使用 IMAP 和 Python 获取 n 最近的电子邮件

发布于 2024-10-31 21:24:27 字数 600 浏览 3 评论 0原文

我希望使用 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 似乎是最合适的。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

不乱于心 2024-11-07 21:24:27

sort 命令可用,但不保证 IMAP 服务器支持。例如,Gmail 不支持 SORT 命令。

要尝试排序命令,您需要替换:
M.search(无,'全部')

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 这些是有效的排序键
“到达”/“抄送”/“日期”/“发件人”/“尺寸”/“主题”/“收件人”

注意:
1. 字符集是必需的,尝试 US-ASCIIUTF-8 所有其他字符集不需要 IMAP 服务器支持
2. 还需要搜索条件。 ALL 命令是有效的命令,但有很多命令。查看更多信息 http://www.networksorcery.com/enp/rfc/rfc3501.txt< /a>

IMAP 的世界是狂野而疯狂的。祝你好运

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

独享拥抱 2024-11-07 21:24:27
# get recent one email
from imap_tools import MailBox
with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
   for msg in mailbox.fetch(limit=1, reverse=True):
       print(msg.date_str, msg.subject)

https://github.com/ikvk/imap_tools

# get recent one email
from imap_tools import MailBox
with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
   for msg in mailbox.fetch(limit=1, reverse=True):
       print(msg.date_str, msg.subject)

https://github.com/ikvk/imap_tools

呢古 2024-11-07 21:24:27

这是获取 emailFrom、emailSubject、emailDate、emailContent 等的代码。

import imaplib, email, os
user = "[email protected]"
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()        

This is the code to get the emailFrom, emailSubject, emailDate, emailContent etc..

import imaplib, email, os
user = "[email protected]"
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()        
蓝颜夕 2024-11-07 21:24:27

这对我有用〜

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

this is work for me~

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']

and this is get the newer email function :

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
涫野音 2024-11-07 21:24:27

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

Workaround for Gmail. Since the The IMAP.sort('DATE','UTF-8','ALL') does not work for gmail ,we can insert the values and date into a list and sort the list in reverse order of date. Can check for the first n-mails using a counter. This method will take a few minutes longer if there are hundreds of mails.

    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
追星践月 2024-11-07 21:24:27

要获取最新的邮件:

这将返回第二个返回值中包含的所有邮件号码,该返回值是一个包含字节对象的列表:

imap.search(None, "ALL")[1][0]

这将分割字节对象,通过访问负索引可以获取最后一个元素:

imap.search(None, "ALL")[1][0].split()[-1]

您可以使用邮件号码访问相应的邮件。

To get the latest mail:

This will return all the mail numbers contained inside the 2nd return value which is a list containing a bytes object:

imap.search(None, "ALL")[1][0]

This will split the bytes object of which the last element can be taken by accessing the negative index:

imap.search(None, "ALL")[1][0].split()[-1]

You may use the mail number to access the corresponding mail.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文