Getting n most recent emails using IMAP and Python

前端 未结 5 1021
终归单人心
终归单人心 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条回答
  •  萌比男神i
    2020-12-28 21:24

    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
    

提交回复
热议问题