I'm making a pseudo-database using a .csv file. Essentially what I'm trying to do is when I launch my code, I open the .csv file and read in all values to an array tempDB
, before entering my infinite loop to routinely check if a new email with a certain subject has come in. On each iteration of the loop, I open a .csv writer. I then connect to my gmail, and search for unread emails that match the subject. The Date-time is parsed, and this is what is used to check if the email had been read by this script before. I iterate through the array, checking to see if the new date-time string matches anything in the .csv file (which is contained by tempDB
). If the date-time string doesn't match anything from the tempDB
array, then I perform a certain action. The reason I'm keeping track of the emails this way, and not by having this script set the email to read
is because I have another program that interacts with the same emails on a slower interval. I want for this to be able to ignore emails if they've been seen by this code, but for my other application to mark the emails as read. Below is my code:
import imaplib, time, email, mailbox, datetime, csv
server = "imap.gmail.com"
port = 993
user = "Redacted"
password = "Redacted"
def main():
tempDB = []
infile = open('MsgDB.csv' 'r')
reader = csv.reader(infile)
for row in reader:
if any(row):
tempDB.append(row)
infile.close()
while True:
found = False
outfile = open('MsgDB.csv', 'w', newline='')
writer = csv.writer(outfile)
conn = imaplib.IMAP4_SSL(server, port)
conn.login(user, password)
conn.select('inbox', readonly=True)
result, data = conn.search(None, '(UNSEEN SUBJECT "Test Subject")')
i = len(data[0].split())
for x in range(i):
latest_email_uid = data[0].split()[x]
result, email_data = conn.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = email_data[0][1]
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
date_tuple = email.utils.parsedate_tz(email_message['Date'])
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
local_message_date = "%s" %(str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))
for i in range(len(tempDB)):
if tempDB[i] == local_message_date:
print("Item Found")
found = True
continue
else:
print("Writing to file...")
tempDB.append(local_message_date)
writer.writerow([local_message_date])
for part in email_message.walk():
if part.get_content_type() == "text/plain" and found != True:
#DO THE THING
else:
continue
outfile.close()
time.sleep(30)
if __name__ == "__main__":
main()
The core issue, from what I can see, is that the csv file is never being written to, tempDB is never being appended to. As you'll notice, I've placed debugging print statements for Item Found
and Writing to file...
. However, neither of these ever print, which tells me that the loop is likely being skipped entirely. I do, however, print the Local Message Date
and TempDB
, which always prints the most recent message matching the subject, and TempDB is always empty. Furthermore, the actions that take place in #DO THE THING
do occur. The problem is, it will keep using the same email, even if it should've been written to the .csv file that this script has already read it. What am I doing incorrectly here? Thank you in advance!