0
votes

So I am successful in getting the date for the last email received from the contact in the code below.

Now I am trying to get the date for the last email sent to the contact. As a beginner to the coding/python, I am not able to get it right. I tried to change 'From' to 'To' but it wasn't giving me the right date.

Any idea how should I proceed with this? I have tried looking around and didn't find a solution.

import email
from imapclient import IMAPClient
from datetime import timedelta, date, datetime


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

since_date = date(2016, 1, 1)    

##Search Inbox
messages = server.search(['FROM', '[email protected]', 'Since', since_date])
response = server.fetch(messages, ['RFC822'])
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']))
2

2 Answers

0
votes

The reason you are not getting the right date is because the list is unordered. In order to guarantee that you are getting the right one, you need to first sort it.

Try this quick step-by-step solution coded in a friendly style for newbies:

# Getting your response keys
response_keys='cabd' 

# Your response keys converted into list
msg_ids = list(response_keys) 
print(msg_ids) # result: ['c', 'a', 'b', 'd']

# Here your are sorting the list in place using built-in sort function
# The syntax is: list.sort(reverse=True|False) and the default is True
msg_ids.sort() 
print(msg_ids) # result: ['a', 'b', 'c', 'd']

# Finally, grab the last item in the list
last_msg_id = msg_ids[-1] 
print(last_msg_id ) # result: d
0
votes

How about this method? Is not very simple but it does the job.

  • Make a List of the messages sent to a certain user
  • Get the items from it (the first one is the most recent message sent)
  • Use the id of the first message to do a Get, using metadata and date as parameters for format and metadataHeaders

  • Get the value of the first item of the headers returned

    service = build('gmail', 'v1', credentials=creds)


    messages = service.users().messages().list(userId='me', q='to:[email protected]').execute()

    items = messages.items()[1][1]

    lastmess = service.users().messages().get(userId='me', id=items[0]['id'], format='metadata', metadataHeaders='Date').execute()
    print (lastmess['payload']['headers'][0]['value'])

Result:

Wed, 11 Mar 2020 16:10:32 +0100