AppleScript for Apple Mail to change message background color in a rule

Hello!

I’ve stumbled onto an issue with how Apple Mail’s rules are handling my AppleScripts to change the background color of a message.

I have 2 rules in Apple Mail that each run their own AppleScript:

  • Rule #1 will change the background color of the message to RED if the sender’s email address is from calendly.com.
  • Rule #2 will change the background color of the message to GREEN if the sender’s email address if from zoom.com.

Below you can see a screenshot of Rule #1, along with its associated AppleScript.

tell application "Mail"
	set theSelection to selection
	set thisMessage to item 1 of theSelection
	set background color of thisMessage to red
end tell

(Rule #2 is nearly identical, but it uses a different domain name and the AppleScript uses “green” instead of “red”.)

The great news is that both of these rules work 100% perfectly fine for incoming messages!

As soon as an incoming message comes into Apple Mail that matches one of the rules, its background color changes to the appropriate color — either red or green! :smiley:

So the AppleScripts are actually working 100% perfectly fine for individual messages! :cowboy_hat_face:

However, this is where the problem comes in:

When I select multiple messages simultaneously in Apple Mail, and then I pull down from the “Message” menu to “Apply Rules”, Apple Mail will only change the background color of ONE of my selected messages… even if several of my selected messages successfully match rules.

My expectation was that when I choose “Apply Rules”, Apple Mail would change the background colors of each of the selected messages to their appropriate colors, if that particular message matched a rule.

But Mail only seems to choose ONE message out of all of my selected messages, and Mail only changes the background color of that one particular message.

Even worse, the message that gets chosen is often a message that doesn’t match any rules at all!

So it seems like my AppleScripts are not written properly to handle this sort of a circumstance.

It seems like my AppleScripts are telling Apple Mail to only evaluate the very first message in a list of messages — regardless of whether that message matches the rule or not.

Is there anything that I could change in my AppleScripts to successfully get Apple Mail’s “Apply Rules” option to always apply the appropriate AppleScript to EACH MESSAGE when I have selected multiple messages simultaneously?

Thank you!