Brizzled

... wherein I bloviate discursively

Brian Clapper, bmc@clapper.org

Append a random fortune to a Mail.app signature

| Comments

I recently switched from Thunderbird to Mail.app, on my MacBook Pro. For years, I’ve been appending random fortunes to the bottom of my email messages, and I wanted this feature for Mail.app, too.

When I used Emacs’ VM to read mail, I merely had to hack together a tiny bit of Elisp and wire it into a VM hook.

When I moved to Thunderbird, I simply wrote a small shell script to concatenate a signature prefix file with a random fortune; I then told cron(8) to run that shell script once a minute, to create a new .signature file. I pointed Thunderbird at that generated .signature file.

But, as it turns out, you can’t point Mail.app at an external .signature file, so the Thunderbird solution won’t work.

The answer is to write a small bit of AppleScript (one of the stranger programming languages I’ve ever used). The AppleScript script:

  • Uses the same signature prefix file that the Thunderbird shell script uses.
  • Concatenates the contents of that prefix file with the output from my fortune program.
  • Tells Mail.app to replace the named signature. (I have more than one signature, and I only want to append a random fortune to one of them.)

Here’s the AppleScript code:

Add random fortune to Mail.app signature Source Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
-- Appends a fortune to the end of a specific signature.
--
-- CONFIGURATION:
-- 1. Change the "fortune" variable to the path of your fortune program.
-- 2. Change the "signatureName" variable to the name of the signature to update.
-- 3. Change the "signatureTemplate" variable to the path to the file containing
--    the signature prefix content.
--
-- INSTALLATION:
-- Use the AppleScript editor to compile to a .scpt file, then install someplace appropriate.
--
-- USAGE:
-- You can wire the script to a key combination, using something like iKey (a
-- third party application). Or, you can run it as a cron job, every so often.
-- e.g., Once a minute:
-- * * * * * osascript /path/to/fortune-sig.scpt

set fortune to do shell script "/Users/bmc/bin/fortune"
set signatureName to "clapper.org"
set signatureTemplate to (POSIX file "/Users/bmc/.sig-preamble.clapper")

set sigPrefix to (read signatureTemplate as text)

on appIsRunning(appName)
  tell application "System Events" to (name of processes) contains appName
end appIsRunning

if appIsRunning("Mail") then
  tell application "Mail"
      tell signature (signatureName as rich text)
          set its content to sigPrefix & fortune
      end tell
  end tell
end if

The final piece of the puzzle is another cron(8) entry, in my personal crontab:

* * * * * osascript $HOME/AppleScripts/fortune-sig.scpt

Conceptually, this solution is the same as the one for Thunderbird; it’s just a different implementation.

Comments