How to determine if user is reading or writing mail?

[strike]This is driving me nuts because I’m sure there’s got to be a fairly simple answer (last time I said that, Nigel posted a 322 line answer … I really shouldn’t tempt fate again!).[strike]
How do I determine the type of window that’s frontmost in Mail.app - I want to know if it’s an incoming message (message viewer or a single message in a window), an outgoing message, or something else (eg preferences pane, activity window, etc.). If it’s an incoming/outgoing message I’d like to know the sender and recipient and if it’s an incoming message I’d like to know which mailbox it’s in also.

I thought this almost worked:

tell application "Mail"
	if (index of front message viewer is 1) then
		try
			set senders to ""
			set messList to selected messages of front message viewer
			repeat with thisEmail in messList
				set senders to sender of thisEmail & ";" & senders
			end repeat
			return "incoming: " & senders
		on error
			return "incoming"
		end try
		
	else 
		return "outgoing"
	end if
end tell

But it turns out that “message viewer” only refers to the main Mail.app window and if you view a single message (eg by double-clicking in the message list) it isn’t a “message viewer” so the code fails annoyingly.

It’s also incomplete in not determining the details of an outgoing message or distinguishin between outgoing messages and prefpanes or determining mailbox for a message being read.

I am not having a Good Coding Day today!
r

PS
I’m using Leopard, 10.5.1 - the Operating System possibilities in the System Info section need updating :slight_smile:

Hi,

just a thought


activate application "Mail"
tell application "System Events"
	tell process "Mail"
		tell window 1
			set x to (count UI elements)
			if exists button "General" of tool bar 1 then
				return "Preferences"
			else if x > 20 then
				return "outgoing"
			else if x > 10 then
				return "message viewer"
			else
				return "incoming"
			end if
		end tell
	end tell
end tell

Wow, cool lateral thinking!! And it works even when the toolbars in question are hidden which surprised the hell out of me.

Unfortunately, if you’ve customised your toolbars (like, say, me) you can change the number of icons which breaks this. I can test for a “send” button to determine between incoming and outgoing but it doesn’t test between incoming and message viewer - I’m not sure how to do that still.

Also, this needs to be quite a general script - will testing for “General” and “Send” break for non-English users or does the localisation stuff magically fix that?

this seems to work for me for out going message

tell application "Mail"
	tell window 1
		if name contains " ” " then
			return "Not composing"
		else
			return "Compsing"
		end if
	end tell
end tell

@mark, you are a lateral thinking genius! Thank you.