Google App Engine for Java で受信したメールをデータストアに保存

Google App Engine for Java でメール受信 の続き。
受信したメールをデータストアに保存するよ!

PMFクラスの作成

PMF.javaを作成。
GAE Code Lab - Chapter 2 Write in DatastorePMFクラスを丸パクリ。

受信メールのJDOクラスの作成

データストアに受信メールを登録するためのJDOクラス、ReceivedMail.javaを作成。

package jp.kuronicle.kuromail.datastore;

import java.util.Date;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class ReceivedMail {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;
    
    @Persistent
    private Date sentDate;
    
    @Persistent
    private String from;
    
    @Persistent
    private String to;
    
    @Persistent
    private String subject;
    
    @Persistent
    private String text;

  //以下にgetterとsetterを記述する。(長いので省略)
}

データストアに永続化するクラスの作成

GAE Code Lab - Chapter 2 Write in Datastore を参考にデータストアに永続化する記述をMailHandlerServlet.javaに追加する。

package jp.kuronicle.kuromail;

import java.io.IOException;
import java.util.Properties;

import javax.jdo.PersistenceManager;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.kuronicle.kuromail.datastore.ReceivedMail;

public class MailHandlerServlet extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {

        PersistenceManager pm = PMF.get().getPersistenceManager();
        Properties prop = new Properties();
        Session session = Session.getDefaultInstance(prop, null);

        try {
            MimeMessage message = new MimeMessage(session, req.getInputStream());

            //JDOクラスに受信メールをセット
            ReceivedMail mail = new ReceivedMail();
            mail.setSentDate(message.getSentDate());
            mail.setFrom(message.getFrom()[0].toString());
            mail.setTo(message.getAllRecipients()[0].toString());
            mail.setSubject(message.getSubject());
            mail.setText(this.getText(message.getContent()));
            
            //データストアに永続化
            pm.makePersistent(mail);

        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            pm.close();
        }
    }

    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;
    }
}

ローカルで動作確認

プロジェクトを右クリックして、[Run As]-[3 Web Application]。
http://localhost:8888/_ah/admin にアクセス。
「Inbound Mail」からテストメールを送る。
「Datastore Viewer」にてデータストアを確認。日本語文字化けしとるー。

デプロイして動作確認

プロジェクトを右クリックして、[Google]-[Deploy to App Engine]。
完了したら、「<なんでも>@<アプリケーション名>.appspotmail.com」宛にメールを送る。
アプリケーション管理画面の「Dtatastore Viewer」にて確認。今度は日本語ちゃんと出てたー!

意外と簡単でした

プログラム初心者の自分でも簡単にメール受信アプリが作れてしまった…。
次回は、送信側のプログラムを書いてみたいなー。