Getting n most recent emails using IMAP and Python

前端 未结 5 1031
终归单人心
终归单人心 2020-12-28 20:56

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 imapl         


        
5条回答
  •  清酒与你
    2020-12-28 21:29

    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
    

提交回复
热议问题