Using AppleScript to Open a Specific Mailbox in Apple Mail (MacSparky Labs)

Shortcuts for iOS 16 is adding a feature that lets you open a specific Mailbox in Apple Mail on your iPhone or iPad. Shortcuts for Ventura, however, doesn’t have that function. What gives? Never fear. Sparky figured out a way to duplicate the feature using AppleScript…

This is a post for MacSparky Labs Level 3 (Early Access) and Level 2 (Backstage) Members only. Care to join? Or perhaps do you need to sign in?

Using Keyboard Maestro and AppleScript to Eject External Drives

I’ve been using a laptop + monitor setup for a while now, and I like it more than I expected. The last time I tried this, I had lots of problems getting the Mac and monitor to talk to each other when I’d plug it in. I prefer to keep the laptop closed when doing this (often called “clamshell” mode), and for years macOS did not like that.

Maybe it is the Apple silicon switchover or improvements to macOS, but that’s no longer a problem. I plug it in and start typing.

However, another friction point is disconnecting. I have a Time Machine and external storage drive connected to my Mac when attached to the monitor. It’s important that I properly dismount those drives before unplugging. (Just yanking a drive out of your Mac is a terrible idea.)

So … dismounting. There are several ways to pull it off. You could go in the Finder and eject the drive under “Locations” in the Sidebar. There is a handy little Eject button next to each removable drive. (In my case, Dagobah is my Time Machine Drive, and Batuu is my extra storage.) This solution works but is tedious.

There are also some excellent apps to solve this problem. My favorite is EjectBar. This is a menu bar app that, once you click it, lets you eject from the menu bar, saving you a trip to the Finder. A power tip with EjectBar is to Command-Click the menu bar icon, and it automatically ejects all connected drives.

I wanted, however, something more automated. So I made a simple AppleScript that ejects all external drives. Here’s the script:

try
tell application "Finder"
eject the disks
display dialog “Successfully ejected disks.” buttons {“Close”} default button “Close”
end tell
on error
display dialog “Unable to eject all disks.” buttons {“Close”} default button “Close”
end try

As AppleScripts go, this one is pretty basic.

I run this script as part of a Keyboard Maestro Macro. First, it quits all applications. I do this because I have very particular screen setups when I connect to the big monitor. I prefer to close everything out when disconnecting. (I have separate scripts for setting up screens on the laptop screen or the monitor when I plug back in.) Then I eject the drives by running the above AppleScript. I use the Hyper Key plus Q to activate it (⇧⌃⌥⌘Q). I’ve also mapped it to a button on my Stream Deck, which is how I usually activate it. This is the method that has stuck with me. When I’m ready to take the laptop, I push the button, wait a moment, and then unplug and head out. It really isn’t much trouble at all.

Here’s a download link to the Keyboard Maestro Macro.

If you’d like to get better at Keyboard Maestro, I’m putting up a $5 discount code on the Keyboard Maestro Field Guide for one week. Use code KMLAPTOPWARRIOR. 🙂

And here’s a screenshot of the Macro:

Script Debugger 8

It’s a sad commentary on my AppleScripting lately that I just realized ScriptDebugger released version 8 several months ago. Script Debugger is the AppleScript tool that Apple should have released. It’s been in development for 26 years, and it continues to impress.
The most significant change in Script Developer 8 is is support for macOS Big Sur and M1 Macs. Script Debugger 8 runs natively on M1 Macs and generates native standalone script applications for M1 and Intel Macs.
Other new features in Script Debugger 8 include support for Dark Mode, display themes, a reimagined facility for generating standalone script applications that supports code signing and notarizing.
My favorite feature continues to be its fantastic dictionary support. Anytime I hit a thorny problem with AppleScript, the ScriptDebugger dictionaries come to my rescue.
Script Debugger offers a fully functional 20-day free trial. Script Debugger switches to “Lite” mode when the free trial ends, where some of Script Debugger’s advanced features are disabled. Just using the free Lite mode, Script Debugger is far superior to Apple’s Script Editor.

Updates and Improvements to the Salutation AppleScript for Apple Mail

My relationship with Apple Mail isn’t love so much as familiarity. However, every time I think about walking out on Apple Mail, I think about our long and complicated relationship, and how much work I’ve put into it with things like my salutation AppleScript.

The Updated Script

Using a combination of AppleScript and TextExpander, I’m able to automatically insert an email salutation by typing “xhi”. This is really useful and something I run multiple times a day. The original post and explanation on how it works is still good. However, the script has altered a bit. You can download the updated version, called “xnm” (“X Name” in my head) here. I suggest running it as an embedded TextExpander snippet so you can combine it with a variety salutations like “Hi”, “Hello”, “Dear”, “Hey”, and whatever else floats your boat. Also, you can download the TextExpander group with both the “xnm” and “xhi” snippets here. That should be all you need to get this rolling.

But What About Multiple Recipients?

Reader Mark Bramhill had that exact question and came up with two variations of this script. The first will make a salutation for everyone in the “To:” field. If you regularly (or occasionally) send email to multiple recipients, this variant is for you.

Download Multiple Recipients AppleScript

That, however, wasn’t enough for Mark. He made a separate AppleScript that counts the number of recipients. If there is just one recipient, it inserts that person’s name. If there is more than one (including looking at the cc: field), the script instead writes “Y’all”. I thought both of these scripts were pretty clever.

Download the “Y’all” Script

Language Specificity

I also had several emails from non-english speakers about the script not working. The trouble is in this line:

tell text field "To:" of window 1

As you can see, the script is language-specific. In English, the script looks for the “To:” field, but in other languages, that field has a different name. In Dutch, for instance, it’s “Aan:”. If your native language isn’t English, you’ll need to fix that line appropriately.

I do love how this script has taken on a life of its own. This isn’t a testament to anything particularly bright on my part but the utility of a script that auto-salutes every email you send. This feature is so useful that I’m shocked it isn’t baked in to all email applications.

The AppleScript Email Extractor

I spent several hours putting together a super-nerdy Keyboard Maestro script that saves an Apple Mail message as a PDF and then uses some AppleScript to pull data out of the message and use it in the file name. I’ve already added the video, the Keyboard Maestro Script, and the AppleScript to the Keyboard Maestro Field Guide. Below you can watch the video and download the AppleScript here.

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.

AppleScript and the New iWork

Early reports on the new iWork are not good. The general consensus seems to be that in order to make everything compatible, they dumbed down the Mac versions. I’m trying to finish a book right now and preparing for a closing statement on Friday so as you can probably guess, I’m kind of busy. I haven’t had time enough to test the new versions fully.

Clark’s Tech Blog explains there is a significant regression in AppleScript support in the new iWork. I’ve always felt that one of the ironic points about iWork was its general lack of support for AppleScript. Microsoft Office does a much better job of supporting AppleScript and Microsoft even went to the extent of hiring one the best people in the business, Ben Waldie, to write a lot of their automation tools for the Mac version. In this regard, Microsoft is heads and shoulders above Apple.

It’s concerning to see that this new version of iWork has not only not moved forward on automation but instead backwards. I don’t use a lot of AppleScript in iWork and, frankly, I don’t know what the percentage of people is the do. However, for those people that do use AppleScript, it is huge.

On the subject of iWork, I did spend a half hour playing with the new collaboration features and while the feature works as demonstrated during yesterday’s keynote event, they certainly are not as fast as they were during the keynote event. I’m going to have a lot more to say about this in the coming days.

 

Switching Screen Resolutions in Mountain Lion

Recently I bemoaned the ponderous way in which Mountain Lion switches screen resolutions. I often shoot screencasts in less than optimal resolution and the multiple clicks and keypresses required are vexing. David Kreindel heard my call and answered. David pointed me to this Display Menu, a handy app that brings back some old functionality. Does this look familiar.


Screen Shot 2012-10-22 at 8.53.05 PM.png

If that isn’t enough, David also put together a simple AppleScript to speed up the process. Copy the below into AppleScript editor and go nuts. Thanks David.

--This script only works on OS X 10.8; This is due to GUI changes from 10.7 to 10.8

--launches System Preferences to Displays pane

tell application "System Preferences"

activate

set current pane to pane "com.apple.preference.displays"

end tell

tell application "System Events"

--Ensures window is on Display tab, not Color tab

click radio button "Display" of tab group 1 of window 1 of process "System Preferences"

--Ensures Resolution preference is "Scaled" to select resolutions

click radio button "Scaled" of tab group 1 of window 1 of process "System Preferences"

--Sets the resolution to whatever is in row 9 for the primary display; 1280 x 720

select row 9 of table 1 of scroll area 1 of tab group 1 of window 1 of process "System Preferences"

--Change "row 9" to whatever row corresponds to desired resolution

end tell

--Quits System Preferences

tell application "System Preferences"

quit

end tell

Create OmniFocus Tasks with AppleScript

Sometimes efficiency becomes the enemy. Because I’m now a believer in automating document filing via Hazel and OCR, I sometimes get myself in trouble. A case in point is my life insurance bill. It arrives every quarter. I used to scan it and then name it in my Action folder with a TextExpander snippet, which resulted in it getting sent off to a nested folder somewhere. At the same time I’d record an OmniFocus quick entry to pay the bill. It was all second nature.
These days, I use a Hazel rule that looks at the contents of this invoice and names it and files it without me having to trouble to rename the file manually. Put simply, once I scan it, I never see it again unless I go looking for it. The problem is I keep forgetting to create the OmniFocus entry to pay the bill. That’s bad. (Especially if I get hit by a bus, which would only add one more problem to cascading badness.) We can’t have that.

I decided to create an AppleScript that automatically creates an OmniFocus task when this Hazel rule triggers. After a lot of head scratching, trial and error, and even some help from friends at the Omni Group and Ben Waldie (my AppleScript Sensei), I’ve cobbled one together. Here is a screenshot and the AppleScript code.


-- Lovingly crafted by David Sparks, The Omni Group, and Ben Waldie -- macsparky.com

set theDate to current date
set theTask to "Pay Life Insurance"
set theNote to "Lovingly Scanned by your Mac on " & (theDate as string)

tell application "OmniFocus"
tell front document
set theContext to first flattened context where its name = "Tech"
set theProject to first flattened project where its name = "Finance"
tell theProject to make new task with properties {name:theTask, note:theNote, context:theContext}
end tell
end tell

To test the rule, open AppleScript Editor and copy it in. You need to change the context and project names to something that is in your OmniFocus library. Once you trigger it, AppleScript will create a new task in the designated project with the designated context. The task also gets named and the Note field will include the text “Scanned on {today’s date}”. This just happens. Don’t believe me? Go look in your OmniFocus project afterward.

I use this script directly in Hazel. Specifically, when I’ve got a scan that requires future action, I add an AppleScript Hazel action at the end to run this script. After Hazel gets done naming and filing my document, it creates a handy OmniFocus task. Below is my life insurance Hazel rule screenshot to demonstrate.


I’ve modified several versions of the script to handle the variety of documents I scan and OCR that require an automatic OmniFocus action. Creating an OmniFocus task with a script is damn useful. You could use this in a lot of contexts outside of document filing. You’re welcome.

Below is a download link for the Hazel rule. Go nuts.

Download Sample Hazel Rule