Google App Engine for Java でメール受信

Google App Engin for Java でメール受信のサンプルを作ってみた。

実装

以下のサイトで紹介されている通りに実装して終了。
App Engine でメイル受信 - hidemonの日記
本家は以下。ほぼ同じ内容。
Receiving Email - Google App Engine - Google Code

ローカルで動作確認

プロジェクトを右クリックして、[Run As]-[3 Web Application]。
http://localhost:8888/_ah/admin にアクセス。
「Inbound Mail」からテストメールを送る。

あれれ、エラーが発生

javax.mail.internet.MimeMultipart cannot be cast to java.lang.String

どうやら、msg.getContent()の返却値はMimeMultipart型らしく、Stringには変換できないらしい。

対策

以下のページを参考にgetTextメソッドを書き換えてみたよ。今回は添付ファイルを考慮しなかった。
標準入力からMimeMessageを取得し、メール情報を取得するクラス | PowerBEANS Lab

private String getText(Object content) throws IOException, MessagingException {
    String text = null;
    StringBuffer sb = new StringBuffer();

    if (content instanceof String) {
        sb.append((String) content);
    } else if (content instanceof Multipart) {
        Multipart mp = (Multipart) content;
        for (int i = 0; i < mp.getCount(); i++) {
            BodyPart bp = mp.getBodyPart(i);
            sb.append(getText(bp.getContent()));
        }
    }

    text = sb.toString();
    return text;
}

メソッドの引数がMimeMessageからObjectに変わったので、doPost内の呼び出しも以下のように変更。

    System.err.print(getText(message.getContent()));

再度、ローカルで動作確認

subject:SubjectTest
from:fromtest@test.com
to:totest@test.com
to:cctest@test.com
body:---->
本文です!本文です!
body:<----

何故か本文が2個表示される…。
getTextメソッド内のfor文が2回動いてるっぽい。本文が2つ入るのは仕様?

デプロイして動作確認

プロジェクトを右クリックして、[Google]-[Deploy to App Engine]。
完了したら、「<なんでも>@<アプリケーション名>.appspotmail.com」宛にメールを送る。
アプリケーション管理画面のLogsでログを確認。

05-15 08:25AM 44.885 /_ah/mail/test■app-name.appspotmail.com 200 19ms 16cpu_ms 0kb
See details
0.1.0.20 - - [15/May/2010:08:25:44 -0700] "POST /_ah/mail/test■app-name.appspotmail.com HTTP/1.1" 200 0 - - "app-name.appspot.com"
W 05-15 08:25AM 44.895
[app-name/1.341969760703445336].<stderr>: Date:Sat May 15 15:25:43 UTC 2010
W 05-15 08:25AM 44.895
[app-name/1.341969760703445336].<stderr>: subject:TestSubject
W 05-15 08:25AM 44.895
[app-name/1.341969760703445336].<stderr>: from:"Kuro" <送信元メールアドレス>
W 05-15 08:25AM 44.895
[app-name/1.341969760703445336].<stderr>: to:test■app-name.appspotmail.com
W 05-15 08:25AM 44.895
[app-name/1.341969760703445336].<stderr>: body:---->
W 05-15 08:25AM 44.898
[app-name/1.341969760703445336].<stderr>: This is message body.
??????????
W 05-15 08:25AM 44.898
[app-name/1.341969760703445336].<stderr>: body:<----

今度は本文が1つだけだった。しかし、日本語が文字化け…。
次回はメールの内容をデータストアに保存できるよう改造してみる予定。