Automators 2: Use AppleScript to Insert Recipient's Name

video

#1

#2

I’ve been using text expander for years and this still blew my mind, it’s such a cool marriage of AppleScript and text expansion.

I’ve been using it all day and I ran into one minor issue, one of my recipients had their name listed on their email address last_name,First_name, so the script was returning her last name. I modified the script to take this type of situation into account, let me know what y’all think!


#3

Yeah I had to make a fix as well.


#4

That is so cool, but I still have a minor problem.

Is there a command to use word 1 and word 2? Let’s say I have Dr. David Livingstone and I would like to check the text for “Dr.” and than use Dr. and the lastname. I tried to look for that in the internet but I could not find it. And doesn’t work :slight_smile:


#5

This functionality more or less built in to MailMate. With MailMate, there is a function called “insertFormatString”. You can create a string of commands all triggered by a key command. It looks like this in the keybindings file:
“x” = ( “reply:”, “insertFormatString:”, “Hi ${to.name.first},\n\n”);

This will allow me to reply to an email by hitting the “x” key, pre-populated with some text that says, “Hi, firstname”.


#6

Then you can add another if statement to the snippet, like this:

-- TextExpander snippet to add recipient's name to email
-- based on http://macsparky.com/blog/2015/6/automatically-add-recipients-name-to-email-with-textexapnder [sic]
-- updated to handle hyphenated first names properly
-- ( Original version would return Young for Young-Hee .  This version returns Young-Hee. )

set theResult to ""

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
					set theResult to word 1 of theToRecipient
					if (count words of theToRecipient) is greater than 1 then
						if character ((length of word 1 of theToRecipient) + 1) of theToRecipient is "-" then
							set theResult to theResult & "-" & word 2 of theToRecipient
							if (count words of theToRecipient) is greater than 1 then
								if (theToRecipient contains "Dr.") then
									set theResult to word 1 of theToRecipient & " " & last word of theToRecipient
								end if
							end if
						end if
					end if
				end if
			end if
		end tell
	end tell
end tell

return theResult

I added this part:
35

You can add more if statements like this. For example.

if (count words of theToRecipient) is greater than 1 then
	if (theToRecipient contains "Hogg") then
		set theResult to "Commissioner Hogg"
	end if
end if

Resulting in “Hi Commissioner Hogg”

I couldn’t test it because I don’t use Mail for my email.