Automatically Add Recipient’s Name to Email with TextExpander

I occasionally have need of a TextExpander snippet to automatically add the first name of an email recipient to the body of an email. Over the years, I’ve made lots of snippets that have a fill-in field asking me to type in the recipient’s name but wouldn’t it be great if the tiny robot inside my Mac did it for me? To a certain extent, this quest has been my white whale and I’ve been plunking away at it when the mood struck me for the past year. I initially went down the road of AppleScript, which never worked consistently. Ultimately, I found success using System Events. Below is the AppleScript code for System Events that pulls the first name from your recipient and types it in the subject line or body of the message.

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

I owe many thanks to Ben Waldie (@AppleScriptGuru) for his assistance in getting this to work. I also had a lot of help on this from Greg Scown at Smile (@macgreg). I put this script into a TextExpander snippet designated AppleScript. It looks like this.


Typing “xnm” in an email will insert the recipient’s first name. You can combine them with additional snippets in TextExpander. For example, this snippet …


… is activated in the subject line. It types “Purchase Confirmation”, then hits the Tab Key, jumping to the message body, and then addresses the email to the customer first name and some additional text. Note the phrase “%snippet:xnm%” runs the prior snippet to drop the name in the text. This allows you to run an AppleScript inside a text snippet, which I thought was particularly clever.

Click HERE to download these snippets.