Automators 2: Email Automation

Hi, I’m starting to dabble into TextExpander and AppleScript, adapting the provided snippets and scripts to my needs, but I cant seem to use the applescripts correctly.

As an example, I wanted to edit Davids “recipients name script” and add an “else” parameter, when the recipients name consists of 3 words (fe. “Dr. John Smith”) to return the third word from the name, but I cannot get it to work. This is what I tried:

tell application "System Events"
tell process "Mail"
	tell text field "To:" of window 1
		if UI element 1 exists then
			set theToRecipient to (value of UI element 1)
			if (count words of theToRecipient) is 2 then return word 2 of theToRecipient
		else
			if (count words of theToRecipient) is 3 then return word 3 of theToRecipient
		end if
	end tell
end tell

end tell

Doesn’t work. Can someone help? Thanks!