GMail in the shell

Here are a couple of nifty (I think) bash functions which probably won’t work for anyone else. The first one checks GMail1 and reports unread messages on the command line, the second one keeps a vigilant watch for new messages and streams the sender and subject lines using rsstail.

The part that’s probably most likely to fail is the automatic detection of the username and password. It uses Directory Service via the dscl utility to locate the primary email address of the current user, and then locates the password for “accounts.google.com” in your keychain based on the result. This makes a lot of assumptions: your primary email is your GMail address, your current user has it assigned and you’ve stored your password for GMail in your keychain.

It’s easy to fix if it doesn’t work (hardcode your email and password), but it’s not at all secure. Your call, I just figured I’d share the trick…

gmailcheck.shraw
# Check your GMail using the provided Atom feed
# Assumes your GMail is your primary email address for the current user
# Also assumes that you've stored the password for your Google account in the keychain
# You know what happens when you assume... makes an ass out of you and Uma Thurman
gmail() {
	user=`dscl . -read /Users/$(whoami)|grep "EMailAddress:"|sed 's/^EMailAddress: //'`
	pass=$(security find-internet-password -w -a "$user" -s "accounts.google.com")
	curl -u "$user:$pass" --silent "https://mail.google.com/mail/feed/atom"| perl -ne '
		print "Subject: $1 " if /<title>(.+?)<\/title>/ && $title++;
		print "(from $1)\n" if /<email>(.+?)<\/email>/;
	'
}
# version of above using rsstail (brew install rsstail) for a constant watch
watchmail() {
	user=`dscl . -read /Users/$(whoami)|grep "EMailAddress:"|sed 's/^EMailAddress: //'`
	pass=$(security find-internet-password -w -a "$user" -s "accounts.google.com")
	rsstail -a -t -A "$user:$pass" -u "https://mail.google.com/mail/feed/atom"
}
Brett Terpstra

Brett is a writer and developer living in Minnesota, USA. You can follow him as ttscoff on Twitter, GitHub, and Mastodon. Keep up with this blog by subscribing in your favorite news reader.

This content is supported by readers like you.

Join the conversation