Scripting Gmail

I needed to send emails around informing GreyBox users that a new GreyBox version is out. I could use Gmails interface, spend a lot of time, drink some coffee and take some drugs... But!

This is a little guide on how to search Gmail, parse the results and use the results to send some emails.

Python baby!

I love Python and it's freaking cool I can use my favorite language to script my favorite email application. Python Gmail library libgmail will be used.

Get libgmail and install it by doing:

python setup.py install

Query the Gmail email database

The mission is to extract all the emails I got regarding the key word greybox. Here is the code that does that:

import libgmail
import re
from sets import Set

re_email = re.compile('.*"_upro_(.*?)".*')
re_author = re.compile('.*>(.*)<.*')

def getEmails(query):
  ga = libgmail.GmailAccount("amix3k@gmail.com", "mypw")
  ga.login()
  messages = ga.getMessagesByQuery(query, True)

  emails = Set()

  for m in messages:
    auths = m._authors
    r_author = re_author.match(auths).groups()[0]
    r_email = re_email.match(auths).groups()[0]
    emails.add((r_author, r_email))

  return emails

for a, email in getEmails('greybox'):
  print "%s, %s" % (email, a)

Running this script will print out following:

johndoe1@email.com, John Doe 1
johndoe2@email.com, John Doe 2
johndoe3@email.com, John Doe 3

We will put the emails in a file called emails:

python get_emails.py > emails

Now one can filter emails manually and remove some emails of people that already know that GreyBox 3 is out.

Send an email to people

Sending email is rather trivial, here is the needed code that will send an email to everyone in the file emails:

import libgmail

ga = libgmail.GmailAccount("amix3k@gmail.com", "mypw")
ga.login()
def sendEmail(to_email):
  subject = "GreyBox 3 released"
  msg = """GreyBox 3 is released :)

The new version features...

Check out http://orangoo.com/labs/GreyBox/ for more information.

Kind regards,
4mir Salihefendic (http://amix.dk)"""
  gmsg = libgmail.GmailComposedMessage(to_email, subject, msg)
  ga.sendMessage(gmsg)

for l in open("emails"):
  email, author = l.split(", ")
  sendEmail(email)

Save this in a file called send_emails.py and run it:

python send_emails.py

The end

This is the end - the end my friend :) Hope you enjoyed this.

Code · Python 21. Jun 2006
© Amir Salihefendic. Powered by Skeletonz.