Skip to content

Instantly share code, notes, and snippets.

@israel-dryer
Created September 19, 2020 02:08
Show Gist options
  • Save israel-dryer/54e9e914336957fda760572f35467af2 to your computer and use it in GitHub Desktop.
Save israel-dryer/54e9e914336957fda760572f35467af2 to your computer and use it in GitHub Desktop.
Identify undeliverable messages in Outlook
import re
import win32com.client as client
# pattern for identifying email addresses
pattern = re.compile(r'mailto:(\w+\.\w+@company.com)')
outlook = client.Dispatch('Outlook.Application')
namespace = outlook.GetNameSpace('MAPI')
inbox = namespace.Folders['Inbox']
# extract all report type items that related to undelivered mail
returned = []
for item in inbox.Items:
if item.Class == 46 and item.Subject.startswith('Undeliverable'):
addresses = re.findall(pattern, item.Body)
if addresses:
returned.extend(addresses)
# unique addresses to remove from distribution
to_remove = list(set(returned))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment