Insert name of email receipient

I use the below AppleScript in a Keyboard Maestro macro to insert the mail recipients name at the top of the email. But it only works when name is in format 'first name last name' e.g. 'Joe Bloggs'.

Frequently names of email recipients are in the format 'last name, first name' e.g. 'Bloggs, Joe'. How can I edit code so that if names are in format 'last name, first name' then the first name is inserted?

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 greater than 0 then return word 1 of theToRecipient

end if

end tell

end tell

end tell

Between the set theToRecipient... and if (count of words... add:

if theToRecipient contains "," then
	set AppleScript's text item delimiters to ", "
	set theToRecipient to text item 2 of theToRecipient
end if

Note that this way of doing things isn't 100% -- word 1 of "Mary-Anne Smith" will be "Mary" and not the correct "Mary-Anne", for example. If you are getting your address from another source (rather than this being a "Reply" email) see if you get the correct data from there at the same time.

1 Like