受信したメールをパイプでPythonに渡して本文読んだり添付を保存したり

携帯メールでのブログエントリ投稿だったり、ユーザ登録だったり、メールのパイプ処理って結構重要だと思います。パイプさせなくてもcronで定期的にPOPすればいい話ですが、それだとユーザからのリクエストに対してシームレスに反応できないですよね。それはなんかイヤなんです。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, os, email

_mail = email.message_from_file(sys.stdin)

for item in _mail.walk():

if  item.get_content_maintype()==’text’:

_file = open(‘/path/to/save/log.txt’, ‘a’)
_file.write(_mail[‘Subject’]+’rn’)
_file.write(item.get_payload(decode=True)+’rn’)  #body
_file.close()

elif  item.get_content_maintype()==’image’:

_filename = item.get_filename()

_attache = open(‘/path/to/save/’+_filename, ‘wb’)  #添付ファイルを保存
_attache.write(item.get_payload(decode=True))
_attache.close()

Python2.5です。

標準入力で読み込んで、要素(きちんと理解できてないのですが、boundaryで区切ったものってことだろうか)ごとにイテレートして、content_maintypeがtextなのかimageなのかで処理を分岐しています。ちなみに、content_maintypeはExcelファイルだったら「application」になります。

なお、エンコード処理入れてないのとエラー処理入れてないのです。いつものことなのです。