Michael Cordell's Blog

MailMate email message references in org-mode notes

Often when processing my email inbox, I take a note or TODO and then archive an email. Ideally, when creating the note I’d like to reference the email in case I want to read the thread or later on I realize I need to followup. My email client of choice, Mailmate, supports the message:// protocol for each email. MailMate even encourages this referencing, with a Copy as link option in the Edit menu. Given that support, I assumed there would be a way to get the link programmatically with AppleScript. With the link in hand, I wanted to insert it directly into org-mode. Ideally, what I was looking for is this:

NOTE TEXT: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor - Email <– clicking the link opens the email in MailMate

Emacs being emacs, there had to be a way to do this in a few keyboard strokes. The hardest part was getting the AppleScript part right. MailMate’s AppleScript dictionary documentation was thin, so I ended up cribbing the script from this post:

tell application "MailMate"
    set allMessages to messages
    set theMessage to item 1 of allMessages
    return message url of theMessage
end tell

This would reliably give me the URL of the selected message in MailMate as a string. I then turned to the emacs side and built on top of the existing org-mac-link package. Below I define three functions in my doom-emacs config.el file:

Note that the use-package! function is doom-emacs specific and is described here. The functions are defined after org-mac-link has been loaded.

(use-package! org-mac-link
        :after org
        (defun as-get-selected-mailmate-message ()
        (do-applescript (concat "tell application \"MailMate\"\n" " set allMessages to messages\n"
                                " set theMessage to item 1 of allMessages\n"
                                " return (message url of theMessage) & \"::split::Email\"\n"
                                " end tell\n")))
        (defun org-mac-mailmate-item-get-selected ()
        (message "Applescript: Getting mailmate message...")
        (org-mac-paste-applescript-links (as-get-selected-mailmate-message)))

        (defun org-mac-mailmate-insert-selected ()
        (insert (org-mac-mailmate-item-get-selected))))

Notice, I changed the second-to-last line of the AppleScript to add the string ::split::Email. This is the format other org-mac-link functions expect. ::split:: is a token, and “Email” is the displayed text for the link when pasted in org-mode.

Finally, with those commands defined, I added a keyboard shortcut (again using doom’s shortcut specification):

(map! :prefix ","
      (:map org-mode-map
       :nv "e" #'org-mac-mailmate-insert-selected

Now, after typing a note in org-mode while reading an email, I just hit , and then e and a link to the MailMate message is pasted directly into the note.