I’ll not tell you how much time I’ve wasted trying to find a way of using AppleScript to generate a link (file path or URL) to an individual email message in Mail.app. There are a number of solutions on the web but most involve invoking a shell script to run a Spotlight query from the command line. Clever but cumbersome.
There is an easier way providing you use the MailTags extension to Mail.app in combination with AppleScript.
The message id of an email message can be combined with the ‘message://’ protocol to specify a URL for individual email messages. The simple AppleScript snippet below shows you how to easily get the message id for a selected email message in Mail.app. You can then use this URL in your own applications. For example, embed a link to an email message in an iCal event or todo, or even use the URL in web-based applications. I’ve used message URLs to link email messages to actions in my custom-built PHP-based GTD system. Nice.
Copy/paste the following AppleScript into Script Editor. Then run Mail.app, select an email message then run the script. Adapt the script for your own purposes.
tell application "Mail" set theSelectedMessages to selection set the selected_message to item 1 ¬ of the theSelectedMessages set message_id to the message id of the selected_message end tell set message_url to "message://" & message_id open location message_url
This trick only works if you use Mail.app because of the reliance on MailTags. Without it you can use AppleScript to get message ids but MailTags is required to have Mail.app open message URLs. If you use Mail.app anyway then MailTags is a highly useful extension and well worth getting.