The Lamson Project emerged recently, but dealing with emails as always been around. Sending emails can be a pain for other reasons than receiving email is one too. Let’s focus on the second one with a simple demo that posts a picture to TwitPic from an email using Twisted.
Disclaimer, I haven’t tested Lamson but feels more confident to go with a solution built on top of Twisted then another one redoing most of the job using plain asyncore and threads.
We will start by using txmailserver originally built by Duncan McGreggor, a set of tools to set up a basic STMP server, with POP3 support.
Read the file server.tac to see all the boiler plate, I’ll show the interesting parts.
def twitpic_it(dest, message): pass # see bellow domains = { "twitpicit.org": [ Script(r"[a-zA-Z_0-9\-\.]+\+.+", twitpic_it) ] }
It’ll accept any email users that look like: me+mypassword@twitpicit.org
and call the twitpic_it
function. From there we can do whatever we want. No more details on the email treatment.
def twitpic_it(dest, message): username, password = dest.local.split("+", 1) # finding the part which is a picture # and building a temporary file with it file = file_from_message(message) if file is not None: datagen, headers = multipart_encode({ "username": username, "password": password, "message": message["Subject"], "media": file }) request = urllib2.Request( "http://twitpic.com/api/uploadAndPost", "".join(datagen), headers) file.close() urllib2.urlopen(request).read()
There you go, you’re able to twitpic everything you like from any email client. After you’ve set up that on one of your domain of course or you can try it locally using a simplistic Python script: test.py.
$ twistd -ny server.tac
in a different shell:
$ python test.py mypicture.png My message
The server should display the response from Twitpic. Of course this is purely overkill if you can directly use the API.
Email is still an interesting interface for people that aren’t techie at all. For people that sits behind a desk with only that as an interface to the outside world because the IT service decided that you shouldn’t spend your day playing on Facebook or because you are Richard M. Stallman (RMS) himself.
Most of the time a bad usage of emails is made, like answering leads to nothing (the infamous noreply), of you have to visit it inside a browser to do something. Don’t neglect it as a tool that most of the people understand and know how to use it. It means they don’t have to think too much in order to use it.
The code is on Launchpad.