Mail: front message viewer ≠ front window

I don’t know if this is a bug or if I’m just dumb. When there are more than one windows open in Mail, message viewer 1 is not always the frontmost one. It seems Mail index message viewers by their creation time. Try this: leave only one window opened in Mail then run the script below. Open a second window and leave it in front and run the script again.

tell application "Mail"
	get properties of every message viewer
	get properties of message viewer 1
end tell

You’ll see no matter which window is front, Mail will refer to the oldest message viewer as front message viewer. The only way I’ve found to get the correct frontmost message viewer is by running this

tell application "Mail"
	repeat with i in every message viewer
		if window of i is window 1 then get properties of i
	end repeat
end tell

Is there any other way? Is this a bug?

AppleScript: AppleScript 1.10.7
Browser: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en; rv:1.8.1.6) Gecko/20070809 Camino/1.5.1
Operating System: Mac OS X (10.4)

Hi,
don’t know if this helps but have you tried naming the mailbox you want to get messages for? If you specify the mailbox as a variable you should be able to do what you want with it.

tell application "Mail"
	set myinbox to mailbox "Your Mailbox name here"
	set mymessages to every message of myinbox
	repeat with this_message in mymessages
		set mysubject to subject of this_message
		tell application "Finder"
			display dialog mysubject
		end tell
	end repeat
end tell

Does the message have to be open?

It wouldn’t do since my target is visible messages of front window (either messages in a mailbox, smart folder or filtered messages). The script works fine but I wish there was a more elegant solution than using “repeat”. The script (to get messages size):

try
	tell application "Mail"
		repeat with i in every message viewer
			if window of i is window 1 then
				set msg_size to 0
				repeat with this_msg in (get visible messages of i)
					set msg_size to msg_size + (message size of this_msg)
				end repeat
				set msg_size to (msg_size div 1024) + 1
				display dialog "The total size of visible messages is approximately " & msg_size & "k" as text buttons {"okay"} default button 1
			end if
		end repeat
	end tell
on error the error_message number the error_number
	-- don't display error message if the user canceled a dialog within the [try] and [on error] lines above
	if the error_number is not -128 then
		set the error_text to "Error: " & the error_number & ". " & the error_message
		display dialog the error_text buttons {"Cancel"} default button 1
	else
		error number -128
	end if
end try

I believe the syntax you are looking for is:
get the message viewer whose window is equal to 1

Basically each message viewer has a Window associated with it and it is the window that will be frontmost. Window is a property of message viewer.

Browser: 2009 MacBookPro 13
Operating System: Mac OS X (10.7)