So my goal is to find the last email from a contact and enter into a sheet. The current challenge is related to the Gmail part.
So the current code is giving me the desired result. However, some contacts has more than 1000's of email and listing them all of them and then printing out the last one increases the overall compute time.
So thought of reducing the compute time by introducing date range into the search parameters. Now, this is reducing the overall compute time. However, for some contact that has last email received, are beyond the date range, it gives me an Index error:List Index out of range.
I was trying to find a way to expand the date range, till the time the last email from that particular contact is found. Also, to break the loop there will be an end date, because mails beyond that time will be irrelevant. After the last email is found, it goes back to the default date range for the rest of the contacts.
I am kind of lost finding out how to do that. Also, I am a beginner at coding/python, so it's very much possible it beyond my awareness at this point. So any help on this is appreciated. :)
import email
from imapclient import IMAPClient
from datetime import date
from dateutil.relativedelta import relativedelta
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')
#search INBOX
m = -6
since_date = date.today() + relativedelta(months=m-1)
end_date = date(2016, 1, 1)
messages = server.search(['FROM', 'email_i_want_to_search@gmail.com', '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']))