applescriptrulesapple-mail

Mail.app's rules are sending the wrong messages to AppleScript


I have the following AppleScript triggered by a Mail.app rule:

using terms from application "Mail"
    on perform mail action with messages theMessages for rule theRule
        repeat with msg in theMessages
            set theText to subject of msg & return & content of msg & date sent of msg
            display dialog (theText)
        end repeat
    end perform mail action with messages
end using terms from

If I select a message, right click and choose 'Apply Rules' it works properly. However, if the script is triggered by an incoming message, it seems to have a random message in theMessages.

Here is the rule:enter image description here

How do I get the right message?

I'm using High Sierra with Mail 11.2.


Solution

  • Apparently, handling incoming messages with rules is an asynchronous process. When on perform mail action is called, the message is not yet completely updated. Only partial data is available immediately.

    A possible workaround would be to add a delay 1 into the script. This give Mail a second to finish updating the message. Here is what the script then looks like:

    using terms from application "Mail"
        on perform mail action with messages theMessages for rule theRule
            repeat with msg in theMessages
                -- delay a bit of time for msg to load
                delay 1
    
                set theText to subject of msg & return & content of msg & date sent of msg
    
                — do other processing
    
            end repeat
        end perform mail action with messages
    end using terms from