I try to handle as much of my incoming emails automatically as possible. For the vast majority of cases this is easily done with a few filters, labels and folders I set up on protonmail.com (love it by the way, go check them out! You can even write advanced Sieve filters.).

Recently however, I hit a case where I wanted to process the content of specific mails. For this I set up a rule in Mail.app on my local Mac to trigger an AppleScript. This is hardly anything new (AppleScript has been around since 1993) but has proven to be quite useful. I just use it to trigger a Python script. From there on everything I want to do is possible.

So here’s the snippet I use to combine the content of all emails the rule applied to. This blob of text is then handed over to the Python script for processing.

using terms from application "Mail"
    on perform mail action with messages messageList for rule theRule
        set mailContent to ""
        repeat with aMessage in messageList
            set this_body to content of aMessage
            set mailContent to mailContent & this_body
            set mailContent to mailContent & "===="
        end repeat
        do shell script "python3 yourAbsolutePathToScriptHere " & quoted form of mailContent
        
        display notification ("Processed emails from rule.") with title "Content scraper triggered."
    end perform mail action with messages
end using terms from

If you want to test this without running the rule, preprend this to the script, select mails in Mail.app and run the script in ScriptEditor.

tell application "Mail"
    set messageList to selection
end tell

using terms from application "Mail"
    perform mail action with messages messageList for rule (missing value)
end using terms from

This is not scalable of course and requires Mail.app to be running, but as in my case the rule did not have to run regularly and reliably 24/7 this little client-side hack proved useful.