Getting n most recent emails using IMAP and Python

前端 未结 5 1017
终归单人心
终归单人心 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 the code to get the emailFrom, emailSubject, emailDate, emailContent etc..

    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()        
    

提交回复
热议问题