Wednesday, December 13, 2017

Overrun Inbox? Not today. Bulk Gmail Management from the Command Line

Every so often an errant program (often powered by cron) will flood my inbox with messages. I use Google to manage my e-mail, so this isn't typically a difficult problem to solve. I run a search like this:

label:inbox subject:(cron /usr/local/bin/badscript)

While Google only shows me the first hundred messages there's an option to select all messages, even those not visible. I click this option, hit the archive button, and bam! my inbox is back to usable.

There's a catch to this: the 'select all' option does not exist in Google's Mail app. This means that if I find myself with a overrun inbox and I'm away from a desktop computer, I'm out of luck.

This happened to me after my last vacation. I found myself on an airplane with the chance to respond to e-mail, but an inbox so overwhelmed with cruft that navigating it was painful. While I made do in that scenario, I promised myself I'd come back to this problem and solve it for good. Here's that solution.

I give you: gmail_tool. gmail_tool is inspired by youtube_tool, a command line program for managing YouTube playlists, but with an emphasis on Gmail. In the same way youtube_tool is a curl command line wrapper around Google's YouTube API, gmail_tool connects up curl and the Gmail API.

Here's some examples of it in use:

# Get a list of all messages from John that talk about Linux
# Note that the -q option takes in any valid search that works
# inside of the GMail Search Box. This is powerful stuff.
$ gmail_tool -a list -q "from:john subject:(linux)" 
....

# Google wants label changes to reference IDs, so get this list of IDs
$ gmail_tool -a labels  | head 
Label_11:designer request
Label_9:chatter
CATEGORY_PERSONAL:CATEGORY_PERSONAL
Label_3:foo stuff
Label_10:cron
IMPORTANT:IMPORTANT
CHAT:CHAT
SENT:SENT
INBOX:INBOX
TRASH:TRASH

# Remove a message from my inbox 
$ gmail_tool -a update -i 1604fdca6faf6497  -r INBOX

# Loop through all messages that meet some search criteria,
# file them under a label and remove them from the inbox.
# The -p insures that all pages of the results will be retrieved,
# not just the first page.
./gmail_tool -p -a list -q 'label:inbox subject:(cron update-foo)' | \
   sed 's/:.*//' | \
  while read id ; do gmail_tool -a update -i $id -l Label_9 -r INBOX ; done

That last recipe is the one I need to rescue my inbox from an exploding script.

I can't tell you how psyched I am to add this tool to my toolbox. I'm actually looking forward to the next time I SPAM myself by accident. There's nothing quite like that feeling of kicking off a single command that replaces tedious work.

You can grab the scripts that power the above here. Feel free to use and customize them as you see fit.

2 comments: