Mimsy Were the Borogoves

Hacks: Articles about programming in Python, Perl, PHP, and whatever else I happen to feel like hacking at.

AppleScript, Mail, and deleted messages

Jerry Stratton, March 28, 2011

One thing I’ve noticed happen occasionally—but not often—with this script is that I sometimes see ghost messages: messages I’ve deleted from my inbox, and no longer appear in my inbox, but do get picked up by AppleScript.

I’m not sure exactly what’s going on here, because the messages do eventually disappear. They just don’t disappear immediately. What appears to be happening is that OS X Mail keeps trashed messages, in its internal SQLite database, in the folder they were trashed from.1 And my guess is that when AppleScript asks for all messages from the inbox, Mail just returns a query on that database.

This is easy to check for in the AppleScript, however. Each message has a “deleted status” on it. If it’s true, the message has been deleted.

So replace the “repeat with pendingMessage…” line with:

  • repeat with pendingMessage in (messages of inbox whose read status is true and deleted status is false)

It seems more than a little weird to be asking Mail specifically to ignore messages that don’t appear to be there in the first place. As far as I can tell, however, they are there, but the OS X Mail GUI is hiding them from you.

In response to Apple Mail on the Desktop with GeekTool: Here’s a simple AppleScript to use with GeekTool to put your inbox on the Desktop.

  1. You can look in this database by running sqlite3 on ~/Library/Mail/Envelope Index. Be careful, though—I’m guessing that you can easily damage your Mail if you run a SQL statement that changes anything.