I’m fairly new to Python and have been using it to make things at work easier for me. I work in I.T. and have to read through a lot of emails to look at the status of different things. One of these is our Yodeck players. I get emails every day about which Yodeck players are offline. They don’t come in 1 single email, but an email for each individual player that is offline. I get a lot of emails daily and I wanted to create a spreadsheet from all of the players that are offline so I have one central place that I can look at them.
I was able to actually retrieve all of the email subject lines from my inbox and place them in a CSV file. This felt pretty good. However, I only want to see the emails that came in the current day and the day before. This is where my hair started to turn gray. I tried all different types of solutions I found online and nothing seems to be working. I either get an error saying that < or > doesn’t work with datetime, or it just returns a blank list and prints [] in cell A1 of the CSV file.
Whenever I remove the date filtering part of the code, the email_date list prints fine with all of the dates populated. So for some reason my filtering is returning an empty list and empty spreadsheet.
Here is what I have (please bare with me):
# Importing modules/libraries
import win32com.client
import os
from datetime import date
from datetime import datetime
from datetime import timedelta
import csv
import pandas as pd
# Variables
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
#Empty Lists
email_subject = []
email_date = []
email_content = []
#find emails
for message in messages:
start_date = message.senton.date() - timedelta(days=1)
start_date = start_date.strftime("%Y, %#m, %#d")
end_date = message.senton.date()
end_date = end_date.strftime("%Y, %#m, %#d")
if message.SenderEmailAddress == '[email protected]' and message.Subject.startswith('[EXTERNAL] [Yodeck] Your') and message.SentOn.date() == start_date and message.SentOn.date() == end_date:
email_subject.append(message.Subject)
email_date.append(message.senton.date())
email_content.append(message.body)
with open("yodeck.csv", "w") as new_file:
new_file.write(str(email_subject))
file = open('C:\Users\jotaylor\Desktop\KAG_Projects\yodeck.csv', 'w', newline="")
with file:
write = csv.writer(file)
write.writerow([email_subject])
for x in email_subject:
write.writerow([x])
file.close()
I was able to convert my datetime variable to the same datetime structure as the Outlook emails. I’m just really lost on why everything returns blank once I apply the date range filtering in the if statement. I know to some it may seem pointless to try and accomplish this, but this is just something I’m doing for me and I’m using it as a way to practice Python on a real world scenario. Any help on this would be appreciated. Thanks in advance.
2