Thursday, January 22, 2009

Automating emails of iCalendar (.ics) files

I was surprised after a period of googling that I couldn’t find a python script to email iCalendar files. More specifically, I was wanting to email a *.ics file as an attachment and if it was received by an Outlook client I would like for Outlook to automatically add the buttons to Accept/Deny/etc just like when sent from Outlook itself.
I found a site that did most the research on this task already but they used Perl. Also, their script creates the email but doesn’t send it.
I wanted to use python since it had all included modules already to both create the message and send it using SMTP. For your pleasure, here is my version of the script.
#!/usr/bin/python import smtplib import os from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders send_from = "your_email@yourdomain.com" send_to = "your_email@yourdomain.com" subject = 'Meeting Invite' msg = MIMEMultipart('alternative') msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.add_header('Content-class', 'urn:content-classes:calendarmessage') msg.attach(MIMEText("See attachement for Meeting Invite.")) icspart = MIMEBase('text', 'calendar', **{'method' : 'REQUEST', 'name' : 'meeting.ics'}) icspart.set_payload( open("meeting.ics","rb").read() ) icspart.add_header('Content-Transfer-Encoding', '8bit') icspart.add_header('Content-class', 'urn:content-classes:calendarmessage') msg.attach(icspart) #print msg.as_string() smtp = smtplib.SMTP('localhost'); smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
This requires an iCalendar file called meeting.ics to already exist in current directory.
This script does the minimum work possible and leaves plenty of room for improvements. For example, it would be nice to have text body of the email be the same as DESCRIPTION in the meeting.ics file so that user can see what the calendar item is about even if their application doesn’t support *.ics files. And it could base Subject off of SUMMARY.
From other web site, it sounds like the email sent isn’t compatible with Mac OSX iCal because they want PUBLISH instead of REQUEST. I guess we can’t please everyone right now.