Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

How to let Python check if there are any new emails in Outlook, check if it has a .pdf attachment, and print the email subject and attachment name?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...