Auto Posting to Delicious from iPhone

Most of my link gathering is done these days on the iPhone. Whether it is finding gems in Twitterific, reading a cool article I want to store as a reference in Byline (RSS Feeds via Google Reader), or just regular Safari browsing.

I don't like the hassle of traditional bookmarks in Safari. I love Delicious. So far I have resorted to just emailing myself and then later manually adding them to my Delicious. This is more arduous than I'd like.

So, I finally did something about it.

Below is a script that I have running on my slice every 30 minutes to read a special email box I have setup that will only get emails from my iPhone within a Safari browser. It will look for unread email, take the subject line as the description and the first line of the email as the url, and post to my Delicious account as a private url tagged with "email-import", so that later, I can easily go through and tag and share.

There are many improvements I'd like to make to this, namely not requiring a separate email inbox, smarter parsing and identification of the url email messages, optional application of tags (second line could easily contain tags that I type in).

This script can also be found as a gist:

## Requires:
## svn checkout http://feedparser.googlecode.com/svn/trunk/ feedparser
## svn checkout http://pydelicious.googlecode.com/svn/trunk/ pydelicious
import sys, os, imaplib, email
from pydelicious import DeliciousAPI, DeliciousItemExistsError

MAIL_IMAP_SERVER            = 'imap.gmail.com'
MAIL_IMAP_SSL_PORT          = 993
MAIL_IMAP_USERNAME          = 'XXXXXXXXXX@gmail.com'
MAIL_IMAP_PASSWORD          = 'XXXXXXXXXX'
MAIL_IMAP_INBOX             = 'Inbox'

dlc = DeliciousAPI(user='XXXXXXXXXX', passwd='XXXXXXXXXX')

class DeliciousIMAPClient(object):
    def __init__(self):
        self.username = MAIL_IMAP_USERNAME
        self.password = MAIL_IMAP_PASSWORD
        self.server = imaplib.IMAP4_SSL(MAIL_IMAP_SERVER, MAIL_IMAP_SSL_PORT)
        self.inbox = MAIL_IMAP_INBOX

        self.server.login(self.username, self.password)

    def process_messages(self):
        status, count = self.server.select(self.inbox)
        (retcode, messages) = self.server.search(None, '(UNSEEN)') 
        for msg in messages[0].split(' '):
            if msg:
                (ret, msginfo) = self.server.fetch(msg, '(RFC822)')
                message = email.message_from_string(msginfo[0][1])
                self._process_message(message)
                self.server.store(msg, '+FLAGS', '\\Seen')

    def _process_message(self, message):
        subj = message['Subject']
        url  = message.get_payload().split()[0]
        print 'Posting "%s" to Delicious' % subj 
        try:
            rs = dlc.posts_add(url=url, description=subj, shared=False, tags="email-import")
        except DeliciousItemExistsError:
            print '\tAlready exists.'

if __name__ == "__main__":
    client = DeliciousIMAPClient()
    client.process_messages()