首页 > 解决方案 > 如何使用 python 搜索主题行中包含字符串的 Outlook 电子邮件?

问题描述

我想计算最近 7 天的 Outlook 电子邮件,其主题包含错误类型以及服务器名称。我是 Python 编码的新手。有人可以帮忙吗?

例如:- 我的收件箱中有邮件,主题如下:

  1. 检查 CP-TEST-DB2 上丢失的备份
  2. 检查 G-PROD-AUDB 上的死锁
  3. LF-PTT-DW1 上的 SQL 错误日志中有错误
  4. 检查 CP-TEST-DB1 上的驱动器空间

因此,我想为每个服务器(例如 CP-TEST-DB2、G-PROD-AUDB)获取主题行为“检查丢失的备份”的邮件,并希望在服务器方面依靠它。就像我对“CP-TEST-DB2”服务器有多少“检查丢失的备份”邮件一样。对于每台服务器,我对“G-PROD-AUDB”等有多少“检查丢失的备份”邮件。

对于“CP-TEST-DB2”服务器,我有多少“检查死锁”邮件。我有多少“检查死锁”邮件用于“G-PROD-AUDB”等等每个服务器......等等错误类型也是如此。每 33 台服务器有 8 种类型的 sql 错误警报邮件?

import win32com.client
import imp, sys, os, re
import datetime as dt
import time

date_time = dt.datetime.now()
print (date_time)

#list of errors
error = ['There are errors in the SQL Error Log on', 'Check for missing backups on', 'Check drive space on', 'Check memory usage on', 'Check deadlock on ']

#list of server
server = ['TEST-AUDB','TEST-AUDB','EUDB','TEST-EUDB','PROD-AUDB','PROD-EUDB']

#setup range for outlook to search emails (so we don't go through the entire inbox)
lastHourDateTime = dt.datetime.now() - dt.timedelta(days = 7)
#print (lastHourDateTime)

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders.Item(2).Folders['Inbox']

messages = inbox.Items
messages.sort("[ReceivedTime]", True)
lastHourMessages = messages.Restrict("[ReceivedTime] >= '" +lastHourDateTime.strftime('%m/%d/%Y %H:%M %p')+"'")
print ("Current time: "+date_time.strftime('%m/%d/%Y %H:%M %p'))

for msg in lastHourMessages:
        subject = msg.Subject
        time = msg.ReceivedTime
        print (s1)```




标签: pythonregexpython-3.xoutlookwin32com

解决方案


您可以使用以下正则表达式:

([\-A-Z0-9]+)$

这将匹配每个大写字母、数字和破折号中的 1 个或多个,直到句子结束。这涵盖了您在问题中提供的所有案例,如下所示

接下来,您可以使用该re模块并遍历字符串列表,使用我上面提到的模式搜索匹配项,并将信息存储在嵌套字典中。

import re

# Example strings
strings = ["Check for missing backups on CP-TEST-DB2",
            "Check deadlock on CP-TEST-DB2",
            "Check deadlock on CP-TEST-DB2",
            "Check deadlock on G-PROD-AUDB",
            "There are errors in the SQL Error Log on LF-PTT-DW1",
            "Check drive space on CP-TEST-DB1"]

# Declare empty dictionary
occurrences = {}

# Iterate over all the examples
for string in strings:
    results = re.search('([\-A-Z0-9]+)$', string)
    # Get the server from the regex match
    server = results.group(0)
    # Remove the server from the string and use strip to get rid of the trailing whitespace
    instance = string.replace(server, '').strip()
    # If the server is still not in the dict, insert it manually
    if occurrences.get(server, None) is None:
        occurrences[server] = {instance: 1}
    # If the server is already in the dict, but not the instance, create the key and initial value for the instance
    elif occurrences[server].get(instance, None) is None:
        occurrences[server][instance] = 1
    # Otherwise, just increment the value for the server-instance pair
    else:
        occurrences[server].update({instance : occurrences[server].get(instance, 0) + 1})
print(occurrences)

希望这可以帮助!


推荐阅读