set selection in Mail without looping ([...] to 1st message of [...])

Hi,

I use this script to get a specific email in Mail selected:


set accountSpecifier to "Google Mail"
set mailBoxSpecifier to "Sent Messages"
set messageIDSpecifier to 181493


tell application "Mail"
	set selectedMessage to 1st message of mailbox mailBoxSpecifier of account accountSpecifier whose id is messageIDSpecifier
end tell

tell application "Mail"
	activate
	if (count of message viewers) is 0 then
		make new message viewer at front
	end if
        -- sets the mailbox
	set selected mailboxes of message viewer 1 to {mailbox mailBoxSpecifier of account accountSpecifier}
end tell

delay 0.2

tell application "Mail"
        -- sets the selection
	set selected messages of message viewer 1 to {selectedMessage}
end tell

This works fine.

However it can take rather long in a mailbox with a lot of mails.

And I think thats because of “set selectedMessage to 1st message of mailbox”
It seems like here the script is going through all emails till a message match the criterion.

This seems a little bit stupid since I already have all the information about the email I need
(accountSpecifier, mailBoxSpecifier, messageIDSpecifier).

Is there a way to change the selection of the message viewer without going through all emails in order to set “selectedMessage” appropriately?

Can I construct “selectedMessage” by myself?

In case of the id identifier you have to use the syntax first message . whose id is
because there no other way to filter messages by id and actually there is only one message which matches the criteria.

To filter multiple messages by a property use something like


itell application "Mail"
	tell mailbox "myMailbox"
		set selectedMessages to every message whose subject contains "myText"
	end tell
	set selected messages of message viewer 1 to selectedMessages
end tell

if you want to open a message instead of only selecting it you can use

open location "message://<messageid>" 

keep in mind that id is something else than message id. Message id is an unique ID from the mail server while id is an identifier in the application mail itself.