Remembering Birthdays

By scott - Last updated: Monday, April 20, 2009 - Save & Share - Leave a Comment

I’m not very good about remembering birthdays, and when I do remember them, I’m usually too lazy to actually do anything about it.  Enter Google Calendar and a little python scripting.

I created a calendar I can put everyons birthday on, and wrote a script that runs once daily and emails everyone who has a birthday that day.  Here is my script, in case you want to do something similar.

#!/usr/bin/python2.5

"""
Reads from a Google Calendar and sends birthday wishes to
people on the calendar.

Title of event on calendar must be persons name
First line of description must be email addy of recipient

Uses the google calender API.  More information here:
http://code.google.com/apis/calendar/docs/2.0/developers_guide.html
"""

import gdata.calendar.service
import gdata.calendar
import datetime
import re
from email.mime.text import MIMEText
import smtplib

# define the Google Calendar I want to see
# I used magic cookie authentication
username = 'some_calendar@domain.com'
visibility = 'private-abcdefg'
projection = 'full'
me = "your.email@domain.com"
subject = "Happy Birthday, "

def mail(birthdaywishes):
  s = smtplib.SMTP()
  s.connect()

  for m in birthdaywishes:
    message = MIMEText(m['msg'])
    message['Subject'] = subject + m['name']
    message['From'] = me
    message['To'] = m['email']

    s.sendmail(me, m['email'], message.as_string())

  s.quit()

def fudgedate():
  """
  query for events by date uses latest date as a non-inclusive bound
  so, if I want todays events, I need to set tomorrow as the latest date
  in my query.  Value needs to be a string.
  """
  return str(datetime.date.today() + datetime.timedelta(days=1))

def main():

  # query calendar
  query = gdata.calendar.service.CalendarEventQuery(username, visibility, projection)

  # some trickery to query only for todays events.
  query.start_max = fudgedate()
  query.start_min = str(datetime.date.today())

  # display events for today
  calendar_service = gdata.calendar.service.CalendarService()
  feed = calendar_service.CalendarQuery(query)

  # make a list of dictonaries with recipients information
  recipients = []
  for i, an_event in enumerate(feed.entry):
    # I'm rather proud of this piece of trickery.
    # A regular expression to pick out the email address
    # and seperate it from the message body
    pat = r'([A-Za-z0-9_.+-]+@[A-Za-z0-9-]+\.[A-Za-z]{2,4})\s+([\S+\s+]+)'
    m = re.search(pat, an_event.content.text, re.M)
    recipients.append({'name' : an_event.title.text,
                       'email' : m.group(1),
                       'msg' : m.group(2)})

  if recipients:
    mail(recipients)

if __name__ == '__main__':
  main()
Posted in technobabel • • Top Of Page