1

I am using this piece of code to retrieve the latest email from my Gmail account.

        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");

        try {

            Session session = Session.getInstance(props, null);
            Store store = session.getStore();
            store.connect("imap.gmail.com", "<username@gmail.com>", "<password>");
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            MimeMessage msg = (MimeMessage) inbox.getMessage(inbox.getMessageCount());
            Address[] in = msg.getFrom();
            for (Address address : in) {
                resp.getWriter().println("FROM:" + address.toString());
            }
            Multipart mp = (Multipart) msg.getContent();
            BodyPart bp = mp.getBodyPart(0);
            resp.getWriter().println("SENT DATE:" + msg.getSentDate());
            resp.getWriter().println("SUBJECT:" + msg.getSubject());
            resp.getWriter().println("CONTENT:" + bp.getContent());
        } catch (Exception mex) {
            mex.printStackTrace();
        }

It's working well as a normal Java application. However, when I am using it as a function in my Servlet running on Google App Engine, it only can get the FROM address, the content is null.
msg.getFrom() works fine but msg.getContent() only returns null.
Thanks all for any help.

2 Answers2

0

GAE limits the content types you can receive via JavaMail due to security reasons. Message parts and attachments must be of one of several allowed types, and attachment filenames must end in a recognized filename extension for the type. Here you can find a list of all alowed MIME types. I suppose a content of your mail does not fit these restrictions and that is why you're getting null.

I'm afraid there is no way to bypass this limitation. You should, however, consider if it's possible for your application to use only permitted MIME types. There are plenty of them, so it shouldn't be very restrictive after all.

The other solution you may try is described here.

Community
  • 1
  • 1
Jk1
  • 11,233
  • 9
  • 54
  • 64
  • Thanks for your explanation. Does that mean the content of emails depending on the sender, and we, as a reader, cannot do anything if they send disallowed mail contents?By the way, the email I'm testing is just a plain text but it still does not work. – user1390686 Dec 06 '13 at 01:39
  • Afaik reader cannot fix disallowed mime type. As for the plaintext mails, you're parsing the mail as a MultiPart, while plaintext mails have String as a content, not MultiPart. So I suppose this mail is not as plain as it seems. – Jk1 Dec 06 '13 at 02:16
0

I also has this question.

Please use only permitted MIME types.

or you can try to change the type from your original to the "text/html".

Lily Yu
  • 1
  • 1