How to get Apple Mail to display all emails whose subject begins with a certain text

This sounds bizarrely simple, but I can’t get it to work. Manually you just type the text you want to search for into the find field at the top right of the main Mail window and it will display all emails (inbox, outbox and drafts). But how can this exact same thing be done with a script?
I don’t need anything done to the messages, I just need them displayed.

I tried

set theCode to "3751"

tell application "Mail"
	list every message whose subject begins with theCode
end tell

which is accepted by the compiler, but returns an error when run.

@Fredrik71, I’m not sure what’s wrong but nothing happens when I run this. Shouldn’t the line every message of mailbox "INBOX" whose subject begins with theCode have a command in it, like a verb?

Hi Fredrik71, I really appreciate you taking the trouble to explain all this, but I’m afraid I’m in over my head. I’m going to have to dig into an AppleScript tutorial and find out what exactly are objects, object specifiers, filters, lists and boolean tests, because with my present knowledge I can’t make sense of everything you’re saying. I’ve settled on a temporary solution using key codes, which works fine for now. I’ll post the results as soon as I’m able to write a more elegant solution, but that may take awhile :wink: Thanks for your patience!

Ah, the times when I could spend the whole weekend hacking are long gone, but I’m in no hurry. Thanks for the link.

There is an implicit get command in that line. Writing it is typically optional but sometimes it is necessary to make it explicit so as to force the ‘get’ to occur prior to something else being evaluated. Working with the current date is a common case.

FWIW, every is also typically optional when getting the plural of something, e.g. every message = messages. I should note that there are probably exceptions but I don’t have any examples.