I'm working on a Python script using Outlook MAPI that will allow me to print the email subject and attachment name (if of .pdf format) in the terminal. I used the pythoncom.PumpMessages() but whenever I receive a new email, it still prints all the other emails (given a date range) - which I don't want to happen.
Here's the code I currently have.
import win32com.client as win32
import os
import time
import datetime as dt
import re
import pythoncom
class Handler_Class(object):
def OnNewMailEx(self, receivedItemsIDs):
DateFilter = dt.datetime.now() - dt.timedelta(days = 2)
#Outlook MAPI
mapi = outlook.GetNamespace("MAPI")
#Inbox Folder
inbox = mapi.GetDefaultFolder(6)
#Download Path
path = os.path.expanduser("~\Desktop")
#Sort emails in inbox
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
#Filter emails to go through
DateFilterMsg = messages.Restrict("[ReceivedTime] >= '" + DateFilter.strftime('%m/%d/%Y %H:%M %p')+"'")
for message in DateFilterMsg:
for attachment in message.Attachments:
if attachment.FileName.find(".PDF") > -1:
emailname = str(message.Subject)
print(emailname)
attachmentname = str(attachment.FileName)
print(attachmentname)
print(message.EntryID)
elif attachment.FileName.find(".pdf") > -1:
emailname = str(message.Subject)
print(emailname)
attachmentname = str(attachment.FileName)
print(attachmentname)
outlook = win32.DispatchWithEvents("Outlook.Application",Handler_Class)
#Infinite Loop
pythoncom.PumpMessages()
question from:
https://stackoverflow.com/questions/65906512/how-to-let-python-check-if-there-are-any-new-emails-in-outlook-check-if-it-has 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…