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:
JavaScript
x
37
37
1
Sub OffensiveWords(Item As MailItem)
2
3
Dim arrSpam As Variant
4
Dim strBody As String
5
Dim i As Long
6
7
strBody = Item.Subject & " " & Item.Body
8
9
' Set up the array - use lower case
10
arrSpam = Array("funded", "ppp", "loan", "funding", "word5")
11
12
' Go through the array and look for a match, then do something
13
For i = LBound(arrSpam) To UBound(arrSpam)
14
If InStr(LCase(strBody), arrSpam(i)) Then
15
16
' do whatever here
17
Item.Categories = "Spammy"
18
Item.Save
19
Exit Sub
20
21
Next i
22
23
End Sub
24
25
' use this to test the rules script - select a message and run this macro
26
Sub RunAndRules()
27
Dim objApp As Outlook.Application
28
Dim objItem As Object ' MailItem
29
Set objApp = Application
30
Set objItem = objApp.ActiveExplorer.Selection.Item(1)
31
32
'macro name you want to run goes here
33
OffensiveWords objItem
34
35
End Sub
36
37
https://www.slipstick.com/outlook/filter-messages-offensive-words/
https://pypi.org/project/exchangelib/
JavaScript
1
9
1
from exchangelib import Credentials, Account
2
3
credentials = Credentials('john@example.com', 'topsecret')
4
account = Account('john@example.com', credentials=credentials, autodiscover=True)
5
6
for item in account.inbox.all().order_by('-datetime_received')[:100]:
7
print(item.subject, item.sender, item.datetime_received)
8
9