Lazy Geeks Rejoice: Email Mom Without the Effort of Emailing Mom

Posted on February 6, 2009

Mom, I’m sorry if you ever read this. I love you, I really do. You keep asking me to send you emails all the time and I just don’t know what to say. So this is me being clever and a little cheeky. I hope you enjoy it some how.

I know I will.

So, lazy sons of mothers who continually ask you to send them an email once in a while; you dogs out there who couldn’t remember where their head was if it wasn’t attached to your necks; and those of you who just can’t be bothered — rejoice! I finally got around to doing what I said I should do for years: write a script to replace my duties as a son and make my mother happy. And now I am sharing it with you for your entertainment/pleasure/use.

#!/usr/bin/env python

import os
import mechanize
import subprocess
from BeautifulSoup import BeautifulSoup

SENDMAIL = '/usr/sbin/sendmail'
MOMS_EMAIL = 'mom@mom.com'
MY_EMAIL = 'my@email.com'
SUBJECT = 'Hey mom'

def get_mom_letter_html():
    """
    Fetch result of submitting letter form at
    http://momletters.com
    """
    br = mechanize.Browser()
    br.open('http://momletters.com/')
    br.select_form(name="form1")
    br['DropDownList2'] = ['Day-to-day']
    response = br.submit()

    return ''.join(response.readlines())

def get_letter_from_html(html):
    """
    Scrape the letter from the html

    Arguments:
    - `html`: the html to parse
    """
    soup = BeautifulSoup(html)
    soup.prettify()
    box = soup.find('textarea', id="TextBox1")
    return box.string

def send_email(letter):
    lines = ['To: %sn' % MOMS_EMAIL,
             'From: %sn' % MY_EMAIL,
             'Subject: %sn' % SUBJECT,
             'Content-type: text/plainnn',
             letter]
    p = subprocess.Popen([SENDMAIL, '-t'],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE)
    p.stdin.writelines(lines)
    p.stdin.close()

if __name__ == '__main__':
    letter_html = get_mom_letter_html()
    letter = get_letter_from_html(letter_html)
    send_email(letter)

It’s definitely an ugly little script and will likely require some hacking for those of you not fortunate enough to have a working sendmail binary, Python > 2.4, or the Python modules this script depends on (Mechanize and BeautifulSoup). It works best of course if you use your operating system’s task scheduler. Though you might want to limit how often you send them out depending on your mother’s level of senility. YMMV.

You can try sending your comments, criticisms, and tongue-lashings to james at agentultra dot [com]. I accept ZERO responsibility for anyone’s use of this script. If your mother figures you out and takes you to the kitchen by the ear, that’s your own fault. If my mother ever figures this out, I think that will be punishment enough. Enjoy.