Skip to content
Advertisement

Is there anything in Python that can persistently check to see if an Outlook email with a certain subject title came in?

I want to know if there’s anything in Python that can constantly read my Outlook messages every five minutes. I want it to just check my email every 5 minutes (3:05PM, 3:10PM, 3:15PM, etc.) and as soon as an email comes in my inbox saying with a subject line like “Hello what’s up” I want Python to automatically trigger a piece of .py code.

What I know so far

I already know how to access Outlook –

import win32com.client
win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
inbox = mapi.GetDefaultFolder(1)
...
...

Some possibilities

I am currently looking at a couple links such as persistently running Python in the background, listening for oncoming emails with Python, how to trigger a script upon email receipt as well as a Youtube video that talks about how to run a python script upon sending an email.

Hopefully I’ll be able to figure out exactly how to run my Python script upon receipt of email, but in the meantime this question stays open. Thanks in advance.

Advertisement

Answer

thanks for your help. It’s been a month, but I revisited this problem and was able to find a solution. While I couldn’t find a python program that would listen for an Outlook email, VBA in Outlook could listen for an email and then kick off a python script.

My python code was originally geared to edit an Excel spreadsheet directly. So, when I received an email with a certain subject line blah for example, python file main.py would automatically execute and edit an excel file main.xlsx accordingly.

Something to note is that main.xlsx cannot be open at the time the email arrives. If anyone has any guidance on how to have main.xlsx be modified on the chance that the email arrives while it is open, I’d greatly appreciate it.

The below code solved my issue exactly:

Private Sub inboxItems_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
Dim MessageInfo
Dim Result
If TypeName(Item) = "MailItem" Then
    Debug.Print "Arrived"
    If Item.Subject = "Blah" Then
        Const PyExe = """C:...............python3.9latestpython.exe"""
        Const PyScript = "R:......AndersPythonmain.py"
        
        Dim objShell As Object, cmd As String
        Set objShell = CreateObject("Wscript.Shell")
        
        cmd = PyExe & " " & PyScript
        Debug.Print cmd
        
        objShell.Run cmd
        objShell.exec cmd
        
        MsgBox objShell.exec(cmd).StdOut.ReadAll
    End If
End If
ExitNewItem:
    Exit Sub
ErrorHandler:
    MsgBox Err.Number & " - " & Err.Description
    Resume ExitNewItem
End Sub
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement