Wednesday, May 25, 2011

Email Me At...

I have long looked for a feature for Gmail that will delay sending a message until a certain time. Recently I wanted to send a good friend a Happy Birthday message, right when it was her birthday (one second after midnight). If only there was some way to do that...

Luckily, I didn't have to stay up until midnight to do it, but rather cobbled together a nifty Python script that will wait until a given time, then send a message (including HTML if you have it).

#!/usr/bin/env python

import datetime
import re
import smtplib
import time

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

gmail_user = "yourname@gmail.com"
gmail_pwd = "MyP@$$W0Rd"

def mail(to, subject, body):
msg = MIMEMultipart('alternative')

msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject

if '<html>' in body:
msg.attach(MIMEText(re.sub(r'<.*?>', '', body), 'plain'))
msg.attach(MIMEText(body, 'html'))
else:
msg.attach(MIMEText(body, 'plain'))

m = smtplib.SMTP("smtp.gmail.com", 587)
m.ehlo()
m.starttls()
m.ehlo()
m.login(gmail_user, gmail_pwd)
m.sendmail(gmail_user, to, msg.as_string())
m.quit()

if __name__ == "__main__":
while datetime.datetime.today() < datetime.datetime(2011, 5, 24):
time.sleep(1)

mail("someone_else@gmail.com", "subject",
"<html><b>bold body</b> non-bold body</html>")

Things to Note:
  • Line 11-12, you will need to enter your Gmail address, along with your password in plaintext, so be careful.
  • Line 21, If the body of the message you want to send has the tag <html> it will be sent as an HTML message, all tags will also be stripped and a plaintext version will be put in the document as well.
  • Line 36, The date you use needs to be in ISO format, YYYY-MM-DD, if you want you can even add HH, MM, and SS like this:
    datetime.datetime(2011, 5, 24, 13, 5, 19)
  • Line 39: The first param is the address you are sending to, the second is the subject, and the third is the body (with or without html).
Making one of these read from a .csv file could be insanely useful.

    No comments:

    Post a Comment