A while ago David Sparks posted this AppleScript which found the first name of an email address. This could be used in a text Expander snippet to title the email from the address in the “To:” field.
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
This script no longer works. Does anyone know how to fix it?
Look in System Preferences > Security & Privacy > Automation and see if there is an unchecked box that permits “Mail” to control “System Events”. Generally, the first time a script like this is run, a request will pop up from macOS to “permit Mail to control System Events” or vice versa. If the pop up is dismissed or times out, then scripts like this might never work.
Thanks for the suggestion but I can’t see anything that would be stopping it in Security & Privacy. Also, it worked yesterday before I upgraded to the latest version of Catalina 10.15.1.
I solved the problem by using UI Browser and finding out the name of the UI element. The code below now works as before.
tell application "System Events"
tell process "Mail"
-- tell text field "To:" of window 1
-- tell text area 1 of group 2 of group 1 of scroll area 1 of splitter group 1 of window 1
tell text field 1 of splitter group 1 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
Hope that helps anyone who was experiencing the same problem.
I have that script attached to a Text Expander snippet called “xnm”. I then have some other snippets which call that snippet. For example, I have one which is “xhi” and inserts the text “Hi” and then calls my “xnm” snippet to fill in the name. All blantantly copied from Mr Sparks.
For some reason I could not get the above script to work, I used the one from a post on #macsparky and it worked correctly on 10.15.6
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) and (theToRecipient does not contain ",") then
return word 1 of theToRecipient
else if ((count words of theToRecipient) is greater than 0) and (theToRecipient contains ",") then
return word 2 of theToRecipient
end if
end if
end tell
end tell
end tell