如何持续监控 outlook 中的新邮件和特定文件夹中的未读邮件 python

How to continuously monitor a new mail in outlook and unread mails of a specific folder in python

我想检查特定发件人的电子邮件并自动处理它到达的任何地方

但是,在某些情况下,我的 outlook 可能会重新启动,意思是当我收到发件人的邮件并标记为未读时

为了持续监控特定主题的新邮件,我发现了以下代码

import win32com.client
import pythoncom
import re

class Handler_Class(object):
  def OnNewMailEx(self, receivedItemsIDs):
    # RecrivedItemIDs is a collection of mail IDs separated by a ",".
    # You know, sometimes more than 1 mail is received at the same moment.
    for ID in receivedItemsIDs.split(","):
        mail = outlook.Session.GetItemFromID(ID)
        subject = mail.Subject
    print subject   
        try: 
            command = re.search(r"%(.*?)%", subject).group(1)

            print command # Or whatever code you wish to execute.
        except:
            pass


outlook = win32com.client.DispatchWithEvents("Outlook.Application",Handler_Class)

#and then an infinit loop that waits from events.
pythoncom.PumpMessages() 

甚至我想遍历所有未读邮件以检查发件人的邮件是否已到达并处理它(如果找到)

在handler_class

内是否有检查未读邮件添加的功能

或者让我知道任何替代程序

因此,如果您每次重新启动 Outlook 时都重新启动 python 脚本,则将这些行添加到代码中以检查收件箱中的未读电子邮件:

ol = win32com.client.Dispatch( "Outlook.Application")
inbox = ol.GetNamespace("MAPI").GetDefaultFolder(6)
for message in inbox.Items:
    if message.UnRead == True:
        print message.Subject #or whatever command you want to do

将此代码放在代码中 outlook 的定义之前

编辑

对我来说,您发布的代码在我关闭 Outlook 之前效果很好,然后即使我重新打开它,在收到新邮件时我也没有收到任何信息(请参阅我的评论之一)。我猜想用 pythoncom.PumpMessages() 关闭 Outlook "unlink" 的事实。不管怎样,我来帮你检查 class Handler_Class 中的未读邮件,并在你重新启动 Outlook 时重新启动监控。

import win32com.client
import ctypes # for the VM_QUIT to stop PumpMessage()
import pythoncom
import re
import time
import psutil

class Handler_Class(object):

    def __init__(self):
        # First action to do when using the class in the DispatchWithEvents     
        inbox = self.Application.GetNamespace("MAPI").GetDefaultFolder(6)
        messages = inbox.Items
        # Check for unread emails when starting the event
        for message in messages:
            if message.UnRead:
                print message.Subject # Or whatever code you wish to execute.

    def OnQuit(self):
        # To stop PumpMessages() when Outlook Quit
        # Note: Not sure it works when disconnecting!!
        ctypes.windll.user32.PostQuitMessage(0)

    def OnNewMailEx(self, receivedItemsIDs):
    # RecrivedItemIDs is a collection of mail IDs separated by a ",".
    # You know, sometimes more than 1 mail is received at the same moment.
        for ID in receivedItemsIDs.split(","):
            mail = self.Session.GetItemFromID(ID)
            subject = mail.Subject
            print subject   
            try: 
                command = re.search(r"%(.*?)%", subject).group(1)
                print command # Or whatever code you wish to execute.
            except:
                pass

# Function to check if outlook is open
def check_outlook_open ():
    list_process = []
    for pid in psutil.pids():
        p = psutil.Process(pid)
        # Append to the list of process
        list_process.append(p.name())
    # If outlook open then return True
    if 'OUTLOOK.EXE' in list_process:
        return True
    else:
        return False

# Loop 
while True:
    try:
        outlook_open = check_outlook_open()
    except: 
        outlook_open = False
    # If outlook opened then it will start the DispatchWithEvents
    if outlook_open == True:
        outlook = win32com.client.DispatchWithEvents("Outlook.Application", Handler_Class)
        pythoncom.PumpMessages()
    # To not check all the time (should increase 10 depending on your needs)
    time.sleep(10)

不确定这是最好的方法,但它似乎符合您的要求。

不要从 python 监控 outlook,而是尝试为该电子邮件设置 outlook 规则,然后通过 vba 启动 python 脚本。

这是从 VBA 启动 python 脚本的代码。

注:以下代码摘自here.

Sub UruchomBata(MyMail As MailItem)
  Dim Ret_Val
    Dim args As String

    args = "c:\new.py"
    Ret_Val = Shell("C:\python27\python.exe" & " " & args, vbNormalFocus) 
  End Sub

Below this line is the python script for those interested. It is currently set to control the DTR pins on the com1 serial port. The following will need to be save as a yourname.py file

import serial
from time import sleep


conn = serial.Serial('com1',
                     baudrate=9600,
                     bytesize=serial.EIGHTBITS,
                     parity=serial.PARITY_NONE,
                     stopbits=serial.STOPBITS_ONE,
                     timeout=1,
                     xonxoff=0,
                     rtscts=0
                     )
# Wake Modem

conn.setDTR(True)
sleep(3)
conn.setDTR(False)
sleep(1)


conn.close()


# Start talking

try:
    while True:
        conn.write('AT'+chr(13));
        print conn.readline() # readlines() will probably never return.
finally:
    conn.close()