2011年2月5日土曜日

ネットワークカメラからのメールをGAEで受信する

ネットワークカメラTS-LCAMの「動きを検知するとメールを送信する」設定にすると膨大なメールが送られて来てしまうので、メールの宛先をGAE(Google App Engine)にして、間引いて画像を保存したり転送するのはどうだろう。

attachmentsにはファイル名とEncodedPayloadが格納されている。
画像ファイル(バイト文字列)にするにはデコードしなければならない。

下記のプログラム例ではメールでJPEG画像を添付して送ると、キャッシュに保存されて /email_view/ファイル名 で見ることが出来ます。

しかし、TS-LCAMはSMTPのポート設定が出来ないようでOP25BのISPではメールが送れないようだ。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# email_unpack2.py 2011.2.5
import logging
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app

class email_view(webapp.RequestHandler):
    @login_required
    def get(self, filename):
        if filename:
            image_data = memcache.get('filename_' + filename)
            if image_data:
                self.response.headers['Content-Type'] = "image/jpeg"
                self.response.out.write(image_data)
                return
        self.error(404)

class email_unpack(InboundMailHandler):
    def receive(self, mail_message):
        path = self.request.path
        logging.info("path: " + path)
        logging.info("Received a message from: " + mail_message.sender)
        if hasattr(mail_message, 'attachments'):
            for filename, content in mail_message.attachments:
                image_data = content.decode()
                logging.info("filename: %s, size: %d" % (filename, len(image_data)))
                memcache.set('filename_' + filename, image_data, time=60)

application = webapp.WSGIApplication([
    ('/email_view/(.*)', email_view),
    email_unpack.mapping()
], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

0 件のコメント: