Python Forum

Full Version: Trying out the parsing/reading of emails from my outlook
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm dabbling in reading emails from python and have the following code just to get my feet wet in doing so, but wanted to see how i can look for certain key words in the body of emails..

import win32com.client

# import os
# from datetime import datetime, timedelta

outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")

# for account in mapi.Accounts:
# 	print(account.DeliveryStore.DisplayName)
    
inbox = mapi.GetDefaultFolder(6)
inbox = mapi.GetDefaultFolder(6).Folders["Emails 2021"]

messages = inbox.Items

messages = messages.Restrict("[Subject] = 'Software - SAS'")
for message in messages:
    print(message.body)
The displayname i have commented out works and displays my email address/account. And when i run i do get the email body for the 1 email i have in that folder I'm testing with. So i was looking at some other sites and examples and couldnt really find a good working sample on what functions that could be called to search within the body of any email for keywords..

Outlook has great message filters and i use those for placing the emails into their own folders.. But what im testing and playing around with is being able to look thru those emails(eventually) for important emails that may contain certain key words within the body.. Starting off the new year we will be starting off with new projects, so someone could send an email with a subject that has nothing to do with the project, but in the body, there is mention of the project.. so for my first attempt, id like to see if i can run a script that will look in certain folders(in this case that would be "Emails 2021")

Eventually if this is possible, i would like to have a list of keywords/project names or project words that i can search for..

I tried using the .contains but got an error on this code:
for message in messages:
    if message.contains("MFP"):
        print(message.body)
    print(message.body)
So im looking for what the correct syntax for searching within the body for certain words/strings is?