#!/usr/bin/env python """Update Pybloxsom blog using email. Background steps: 1. Setup a standard Unix-style maildir. Either use $ cd; mkdir .maildir; cd .maildir; mkdir cur new tmp Or use the maildirmake command. 2. Get email delivered to it. E.g. I use fetchmail daemon to fetch email from externally hosted inbox. 3. Setup Pybloxsom. As written, this script presumes you have the plugins linebreaks and pyfilenamemtime. Get them from the contrib tarball. 4. Set the correct variables to match your setup. EMAILADDRESS - the email address that is allowed to blog. MAILDIR - the path to your maildir BLOGENTRY - the path to your Pyblosxom entries folder. 5. Test the script from the command line. $ python emailtoblog.py 6. Set the correct permissions and add to cron. For example: */5 * * * * root /etc/cron.five/emailtoblog.py """ import mailbox import datetime EMAILADDRESS = "user@domain.co.uk" MAILDIR = '/home/user/.maildir' BLOGENTRY = '/var/www/website.domain.co.uk/blog/entries/' def read_new_posts(mailpath, emailaddress, parser = "#parser linebreaks\n"): """Read emails and return dictionary of new content.""" mymailbox = mailbox.Maildir(mailpath, \ factory=mailbox.MaildirMessage, \ create = False) newposts = {} for i in mymailbox.items(): try: fromaddress = i[1].get('From') except TypeError: # Script expects messages to conform to RFC2822 standard. # However, let's not choke on spam. continue else: if emailaddress in fromaddress: title = i[1].get('Subject', 'No subject provided') body = i[1].get_payload() # Remove Email autobreaking, this may depend on mailers body = body.replace('\n\n', 'MONKEYMOO').replace(\ '\n', ' ').replace('MONKEYMOO', '\n\n') # Put post together body = title + '\n' + parser + body + '\n' # Put filename together posttime = datetime.datetime.fromtimestamp(i[1].get_date()) timelist = [posttime.year, posttime.month, posttime.day, posttime.hour, posttime.minute] datestring = "" for j in timelist: if len(str(j)) == 1: datestring += '-0' + str(j) else: datestring += '-' + str(j) filename = title.replace(' ', '-') + datestring + ".txt" # Add new post to the newposts dictionary newposts[filename] = body # Delete email from mailbox # (Might be safer to move rather than delete) mymailbox.discard(i[0]) return newposts def write_new_posts(newposts, entrypath): """Write new posts to our to Pybloxsom install.""" for i in newposts: blogentry = open(entrypath + i, 'w') blogentry.write(newposts[i]) blogentry.close() def main(): """Runs the main function if called directly.""" newblogposts = read_new_posts(MAILDIR, EMAILADDRESS) if newblogposts: write_new_posts(newblogposts, BLOGENTRY) # start the ball rolling if __name__ == "__main__": main()