selectinga Mail message in apple script

I’m writing a Mail apple script and I need to select the last message in the INBOX. How do I script that?

It depends on what you mean by last message. The latest received message is number 1:

tell application "Mail"
	set a to properties of (message 1 of inbox)
end tell

Once a new message arrives, it will now be the number 1 message.

If, on the other hand, you are looking for the oldest message still in your Inbox, you would shoot for (message -1 of inbox)

Hope this helps,

Thanks, I did mean the last received message but I don’t think I explained well what I want. I want the script to make Mail actually select the last message in the message viewer window, not just get its properties. Can this be done?

Select it how? Or, for what purpose? If you are looking to tell your message viewer to view it, I do not think that can be accomplished; I sure cannot. What I do is just open the message:

tell application "Mail"
	open (message 1 of inbox)
end tell

It does pretty much the same thing, and is a good reminder when a particular message arrives.

You can select it with GUI scripting, But it will be prone to not getting the right message depending on how and what you are viewing, at the time.

You most likely have to get mail to make sure its viewing the inbox first.

*edit

tell application "System Events"
	set selected of row 2 of outline 1 of scroll area 1 of splitter group 1 of window 1 of application process "Mail" to true
	set selected of row 1 of table 1 of scroll area 1 of splitter group 2 of window 1 of application process "Mail" to true
end tell

Thanks,
That does seem to do it. May I ask how you knew all the numbers of windows and scroll areas etc?
Are there perhaps some apps that can help figure out this sort of things?

a “work around”:

define a rule for all messages, and attach this script,
it (over)writes the ID of every message in a plist file


using terms from application "Mail"
	on perform mail action with messages theMessages for rule theRule
		repeat with eachMessage in theMessages
			do shell script "defaults write last.received.message IDlastReceived " & id of eachMessage
		end repeat
	end perform mail action with messages
end using terms from

with this script you are able to open the last received message


set theID to do shell script "defaults read last.received.message IDlastReceived"
tell application "Mail" to open (1st message of message viewer 1 whose id is (theID as integer))

Have a look at prefab uibrowser its what I use.

that’s a very cool idea! I never thought of doing anything like that.

Thanks!