Quantcast
Channel: Active questions tagged email - Stack Overflow
Viewing all articles
Browse latest Browse all 29758

Get only information of the last mail of the contact from Imapclient

$
0
0

So I am a beginner in Python and coding and trying to build up a code that will give information about the last email received from a contact. Right now what I have gives the output of all the email received from the contact. I just want it to print the last email.

Any suggestions on how to go about it?

import email
from imapclient import IMAPClient

HOST = 'imap.gmail.com'
USERNAME = 'username'
PASSWORD = 'password'
ssl = True

## Connect, login and select the INBOX
server = IMAPClient(HOST, use_uid=True, ssl=ssl)
server.login(USERNAME, PASSWORD)
select_info = server.select_folder('INBOX')

messages = server.search(['FROM', 'email_of_the_contact@gmail.com'])

response = server.fetch(messages, ['RFC822'])

for msgid, data in response.items():
    msg_string = data[b'RFC822']
    msg = email.message_from_string(msg_string.decode())
    print('ID %d: From: %s Date: %s' % (msgid, msg['From'], msg['date']))

Viewing all articles
Browse latest Browse all 29758

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>