Gmailのメール本文(body)の取得

Gmailのメール本文を取得するのに、意外とはまったのでメモ

 

Message を使用するとFromとSubject 他は容易に取れるのにBodyが取れない!!

ってことで大分はまりました。

環境:AndroidStudio2.2.3 API :javax.mail 接続IMAP メールBody:plainText

 

  • MessageクラスのgetContent()で取ると戻り値が空白?

message.getContent()

 

  • getContent()を.toString()すると以下のハンドルを返す?(inputStreamらしい)

message.getContent().toString()

>>>>com.sun.mail.imap.IMAPInputStream@3885acf

 

  • 結果以下の方法で動くことを確認
  1.  以下のおまじないclassを用意(importは聞かれるままに…)

 

public static String readString(InputStream inputStream) throws IOException {

ByteArrayOutputStream into = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
for (int n; 0 < (n = inputStream.read(buf));) {
into.write(buf, 0, n);
}
into.close();
return new String(into.toByteArray(), "UTF-8"); // Or whatever encoding
}

 

  1. bodyを呼び出す

Body = readString(mMessage.getInputStream());

 

 

 

  • メールの取得用メモ

Message mMessage = hogehoge.getMessages();

Email_Number = mMessage.getMessageNumber();
Subject = mMessage.getSubject();
From = mMessage.getFrom()[0]; //1件のみ取得
Body = readString(mMessage.getInputStream());
Date = mMessage.getSentDate();

 

 

Subjectまでは簡単だったのに…。

あとreadString()の引用元が分からなくなったので誰か教えて…。