Search code examples
emailapplescript

How to get applescript to trigger on recieved email?


This is the first bit of scripting I have done. I am trying to get an applescript to copy the body of an email and send it as an imessage. I have this script set to fire with a rule in the mail app

using terms from application "Mail"
    on perform mail action with messages matchmsgs for rule Alertrule
        tell application "Mail"
            set msg to item 1 of matchmsgs
            set msgcontent to (content of msg) as Unicode text
        end tell
        set the clipboard to msgcontent
    end perform mail action with messages
    tell application "Messages"
        
        set targetBuddy to "+12223334444"
        set targetService to (id of 1st account whose service type = iMessage)
        set textMessage to "ALERT: " & (the clipboard)
        
        set theBuddy to participant targetBuddy of account id targetService
        send textMessage to theBuddy
    end tell
end using terms from

the problem I am running into is that it doesn't seem to fire on the receive of an email that fits the rule. When I right click on the email and select "apply rule" I can see the gear spinning on the top bar indicating that the script is running but it doesn't send the imessage. If I then go to script editor and play the applescript it sends an imessage with the body of the email I ran the rule on.

So it seems like it works just not with the automation from mail rules. anyone know where I am going wrong?


Solution

  • At least the Messages part must be inside the perform mail action scope.

    And the clipboard detour is not needed

    using terms from application "Mail"
        on perform mail action with messages matchmsgs for rule Alertrule
            set msg to item 1 of matchmsgs
            set msgcontent to (content of msg) as Unicode text
            
            tell application "Messages"
                
                set targetBuddy to "+12223334444"
                set targetService to (id of 1st account whose service type = iMessage)
                set textMessage to "ALERT: " & msgcontent
                
                set theBuddy to participant targetBuddy of account id targetService
                send textMessage to theBuddy
            end tell
        end perform mail action with messages
    end using terms from