How to flag messages that have a particular word in the body of the message?

How can I flag all messages that contain the word “Override” as follows:

set myReply to "Override"

set theSender to "Me <>"

tell application "Mail"
    set theSelection to selection
    if theSelection is {} then return
    set myList to {}
    repeat with thisMessage in theSelection
        if (extract address from sender of thisMessage) is "" then
            set theOutgoingMessage to reply thisMessage with properties {visible:true, sender:theSender}
            delay 1
            tell application "System Events"
                keystroke myReply
                delay 1
            end tell
            send theOutgoingMessage
            delay 1
            set myList to myList
            delay 1
        end if
    end repeat
end tell

As you can see I only reply to those messages. How can I flag them too within this applescript?

It isn’t quite clear what you’re asking for.

You say you want to ‘flag messages’ that have a particular keyword.

Are you talking about scanning your existing mailboxes to find said messages?
Are you looking to trigger incoming messages via a Mail Rule?
The existing script focussed on selected messages - is that how you want to identify messages to check? How are you invoking this script?

Hi. I think this is what you want, but the question is open to interpretation, and selections are best relegated to testing.

tell application "Mail" to repeat with thisMessage in (get selection)
tell thisMessage to if (extract address from sender) is "" then
	if content contains "Override" then set flag index to 1
end if

end repeat


This is what I meant with flagging emails. Marc_Anthony’s answer worked! Thank you so much.

Screenshot 2023-04-18 at 18.13.39

I really like @Marc_Anthony compact version. I have never thought AppleScript in that way.

Here is my take on it how I would do it.

its flagMessage("", "Analytics", 1)

on flagMessage(senderAddress, searchTag, flagIndex)
	tell application "Mail"
		set thisMessage to its selection
		set thisMessage to item 1 of thisMessage
		if (extract address from sender) of thisMessage is senderAddress then
			if content of thisMessage contains searchTag then
				set flag index of thisMessage to flagIndex
			end if
		end if
	end tell
end flagMessage

I wasn’t questioning the flagging part - that’s easy. It was more how you wanted to invoke the script.

Generally, ‘selection’ is always the best way to do it, hence my question regarding Rules (to flag the messages as they come in).

In either case, this can be done via the standard Mail rules, without needing AppleScript at all: