AppleScript to Link to Apple Mail Message

I’ve always like the way OmniFocus can create links to Apple Mail messages when saving an email as a task. With help from listener Jacob (@evansio), I’ve now got a script that can do that anywhere via a text expander snippet. Here’s the AppleScript:

(*
  Returns a link to the first selected Apple Mail message
*)
tell application "Mail"
  set _msgs to selected messages of message viewer 0
  if (_msgs is not equal to missing value) then
    set _msg to first item of _msgs
    set _msgID to do shell script "/usr/bin/python -c 'import sys, urllib; print urllib.quote(sys.argv[1])' " & (message id of _msg)

    return "message://%3C" & (_msgID) & "%3E"
  end if
end tell

Here is that script embedded in a TextExpander Snippet. I’m using the abbreviation “elink”

Screen Shot 2019-02-05 at 7.19.58 AM.png

That’s it. Once you’ve installed it, just type “elink” in any app that can take a URL and you create a link to the currently selected email message. I use it all the time in Notes and Calendar note fields but it really works anywhere. Here’s a short explanatory video.