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']))
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449

1 Answers1

0

The answer depends on the actual structure of the 'response' object, which isn't entirely clear, but you could try the following instead of the for loop you've tried:

last_msg_id = list(response.keys())[-1]
data = response[last_msg_id]
msg_string = data[b'RFC822']
msg = email.message_from_string(msg_string.decode())
print('ID %d: From: %s Date: %s' % (last_msg_id , msg['From'], msg['date']))

Basically, instead of looping over all of the message ids and all of the data, we've taken the full list of message ids ('response.keys()') and just pulled the last entry in that list, and used that to pull in the rest of the email detail.

katardin
  • 596
  • 3
  • 14
  • I am getting the desired results. However, its also giving me this error. Traceback (most recent call last): File "C:/Users/PycharmProjects/Automate/RelDash-Code.py", line 39, in last_msg_id = list(response.keys())[-1] IndexError: list index out of range – Sourav Chatterjee Mar 06 '20 at 18:14
  • Never mind. I figured out the error. Thanks so much. :) – Sourav Chatterjee Mar 08 '20 at 06:46