简体   繁体   中英

How to search outlook email having string in subject line using python?

I want to count last 7 days outlook emails having subject with error types as well as server name. I am new to Python coding.Can someone please help on this?

For example:- I have mails in my inbox as below subject line:

  1. Check for missing backups on CP-TEST-DB2
  2. Check deadlock on G-PROD-AUDB
  3. There are errors in the SQL Error Log on LF-PTT-DW1
  4. Check drive space on CP-TEST-DB1

So, I want to fetch mails with subject line 'Check for missing backups' for each server(eg- CP-TEST-DB2, G-PROD-AUDB) and want count on it server wise. Like how many "Check for missing backups on" mails i have for "CP-TEST-DB2" server. how many "Check for missing backups on" mails i have for "G-PROD-AUDB" and so on for every server.

how many "Check deadlock on" mails i have for "CP-TEST-DB2" server. how many "Check deadlock on" mails i have for "G-PROD-AUDB" and so on for every server... and so on for error type also. I have 8 type of sql error alert mail for each 33 servers?

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




You can use the following regex expression:

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

which will match 1 or more of every upper case letter, number and dash until the end of the sentence. This covers all the cases you provided in your question, as can be seen here .

Next, you can use the re module, and iterate over the list of strings, searching for a match using the pattern I've mentioned above, and storing the information in a nested dictionary.

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)

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM