Skip to content
Advertisement

Python run script upon mail reception [closed]

I have a .py script which I would like to run automatically upon reception of mail from sender with a certain subject. What would be the best way to achieve this?

Advertisement

Answer

You can use the module exchangelib to access your email, but you can’t just have it listen. You would need to scrape it on an interval. You can also se VBA macros discussed here: https://learn.microsoft.com/en-us/office/vba/outlook/concepts/getting-started/writing-an-outlook-macro An example:

Sub OffensiveWords(Item As MailItem)

Dim arrSpam As Variant
Dim strBody As String
Dim i As Long

strBody = Item.Subject & " " & Item.Body

' Set up the array - use lower case
arrSpam = Array("funded", "ppp", "loan", "funding", "word5")

' Go through the array and look for a match, then do something
For i = LBound(arrSpam) To UBound(arrSpam)
    If InStr(LCase(strBody), arrSpam(i)) Then 

' do whatever here
    Item.Categories = "Spammy"
    Item.Save
    Exit Sub

Next i

End Sub

' use this to test the rules script - select a message and run this macro
Sub RunAndRules()
Dim objApp As Outlook.Application
Dim objItem As Object ' MailItem
Set objApp = Application
Set objItem = objApp.ActiveExplorer.Selection.Item(1)

'macro name you want to run goes here
OffensiveWords objItem

End Sub

https://www.slipstick.com/outlook/filter-messages-offensive-words/

https://pypi.org/project/exchangelib/

from exchangelib import Credentials, Account

credentials = Credentials('john@example.com', 'topsecret')
account = Account('john@example.com', credentials=credentials, autodiscover=True)

for item in account.inbox.all().order_by('-datetime_received')[:100]:
    print(item.subject, item.sender, item.datetime_received)

Advertisement