#!/usr/bin/env python

import mimetypes
import email
import email.Header
import urllib
import time


def get_parts(msgbody):
    """
    Find out body,attached image, and return them.
    msgbody : mime message of email
    """
    
    msg = email.message_from_string(msgbody)
    
    subj_l = email.Header.decode_header(msg.get('subject'))[0]
    enc = 'us-ascii'
    if subj_l[1]:
        enc = subj_l[1]
    subj = unicode(subj_l[0],enc).encode('utf-8')

    body = ""
    images = []
    for part in msg.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        tp = part.get_type()
        if not body and tp.find('text') != -1:
            # body like part was found !!
            body = part
            continue
        if tp.find('image') != -1:
            # Image found!
            images.append(part)
    return body,subj,images

def add_moblog_entry(msgbody,blogbase,passwd):
    """
    Add entry from mail
    
    msgbody  : This argument will be mime message of one email.
    blogbase : This argument will be url for blog.
               Authentication informations(user/pass) must be included.
    """

    body,subj,images = get_parts(msgbody)

    if not body:
        # no body was found
        return

    # Add images
    fns = []
    for img in images:
        filename = img.get_filename()
        if not filename:
            ext = None
            try:
                ext = mimetypes.guess_extension(img.get_type())
            except:
                pass
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'image-%d%s' % (time.time(),ext)
        # Invoke factory to add image
        dt = urllib.urlencode({'id':filename,'type_name':'Image'})
        urllib.urlopen(blogbase+'images/invokeFactory',dt)
        # Send raw content
        dt = urllib.urlencode({'title':filename,'content_type':img.get_type(),
                               'filedata':str(img.get_payload(decode=1)) })
        urllib.urlopen(blogbase+'images/'+filename + '/manage_edit',dt)
        fns.append(filename)
    body_str = body.get_payload(decode=1)
    if body_str.find(passwd) != 0:
        return
    else:
        body_str = body_str.replace(passwd,'')
        while body_str[0] == '\n':
            body_str = body_str[1:]
    body_str = body_str.split('---')[0]
    body_str = unicode(body_str,'iso-2022-jp').encode('utf-8')

    # Add entry
    id = time.strftime('moblog%Y-%m-%d-%H-%M',time.localtime())
    dt = urllib.urlencode({'entry_id':id,'title':subj,
                           'body':body_str,
                           'image_path':'images/' + filename})
    urllib.urlopen(blogbase+'add_moblog_entry',dt)

def main():

    #
    # Please set some information,(host of mail server,etc) to use
    #

    import poplib
    s = poplib.POP3('host.of.mail.server')
    s.apop('yourmailaccount','mailpassword')
    l = s.list()
    if len(l) and l[1]:
        m = s.retr(1)

        msgbody = '\n'.join(m[1])
        add_moblog_entry(msgbody,
         'http://[user]:[pass]@url.of.blog/path2/blog/','password4mail')

        s.dele(1)

    s.quit()

    return

if __name__ == '__main__':
    main()
