Using the following code:
import imaplib
import time
user = '#my username'
password = '#my password'
server = 'imap.gmail.com'
mailbox = 'Inbox'
imap = imaplib.IMAP4_SSL(server)
imap.login(user, password)
while True:
try:
email_count = imap.select(mailbox, True)
results, data = imap.search(None, '(FROM "#TestEmail" SUBJECT "Test")')
print('starting search')
ids = data[0]
id_list = ids.split()
latest_email_id = id_list[-1]
result, data = imap.fetch(latest_email_id, "(RFC822)")
raw_email = data[0][1]
print(raw_email)
print('email found, code will still run but no longer search')
exit()
except:
print("no email found, continuing search")
time.sleep(60)
exit()
The goal is to create a program that I can have running in the background when I am not at my office computer that will allow me to run certain processes when needed.
The issue that I am having is that the code:
Does not seem to refresh the list of emails in the inbox (i.e. if I send the email with the subject that should trigger a response, nothing ever happens (though if the email is already in the inbox when I start the code, the response does happen)).
I can not figure out a way to make the code exit after it has successfully completed the operation once. So basically I am trying to have it search for a particular key, and then once it has found that key and performed a task, it then stops searching for the key.