如何持续监控outlook中的新邮件和python中特定文件夹的未读邮件 [英] How to continuously monitor a new mail in outlook and unread mails of a specific folder in python

查看:28
本文介绍了如何持续监控outlook中的新邮件和python中特定文件夹的未读邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to check for a particular sender email and process it automatically wherever it arrives

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

However, there may be some situation where my outlook was restarted, mean while i received mail from sender and marked as unread

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

For continuous monitor for a new mail for a specific subject i have found the following code

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() 

我什至想查看所有未读邮件以检查发件人的邮件是否已到达并进行处理(如果找到)

Even i want to go through all the unread mails to check whether a mail from a sender has came and process it( if found)

handler_class 中是否有检查未读邮件的功能

Is there any function to check for unread mails to add within handler_class

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

Or let me know for any alternate procedure

推荐答案

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

So if you restart your python script every time your Outlook restart, then add these lines to your code to check unread emails in your Inbox:

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 的定义之前

Put this code before your definition of outlook in your code

编辑

对我来说,您发布的代码在我关闭 Outlook 之前效果很好,然后即使我重新打开它,在收到新邮件时也没有收到任何信息(请参阅我的评论之一).我猜用 pythoncom.PumpMessages() 关闭 Outlook取消链接"的事实.无论如何,我都会过来检查 Handler_Class 类中的未读电子邮件,并在您重新启动 Outlook 时重新启动监控.

For me, the code you posted works great until I close Outlook and then even if I reopen it, I don't get anything when a new message is received (see one of my comments). I guess the fact of closing Outlook "unlink" with pythoncom.PumpMessages(). Anyway, I come around to do both your checking for unread email in the class Handler_Class and restart the monitoring in case you restart 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)

不确定这是最好的方法,但它似乎按您的方式工作.

Not sure it is the best way, but it seems to work the way you look for.

这篇关于如何持续监控outlook中的新邮件和python中特定文件夹的未读邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆