1
votes

I am unable to parse multipart email content. Could someone please help?

I am using tips from posts on stackoverflow to receive and parse email (from gmail) using javamail. Adding activation.jar & mail.jar to Android App

message getContent API returns com.sun.mail.imap.IMAPMessage@423ff878

Which means it's not handled by javamail datasource.

The content looks like:

Content-Type: multipart/alternative; boundary=mimepart_51c2a32167465_82e9b701343f

--mimepart_51c2a32167465_82e9b701343f Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: Quoted-printable Content-Disposition: inline

...text...

--mimepart_51c2a32167465_82e9b701343f Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: Quoted-printable Content-Disposition: inline

http://www.w3.org/1999/xhtml">

--mimepart_51c2a32167465_82e9b701343f--

1

1 Answers

0
votes

The below code given in the JavaMail API FAQ might help:

private boolean textIsHtml = false;

    /**
     * Return the primary text content of the message.
     */
    private String getText(Part p) throws
                MessagingException, IOException {
        if (p.isMimeType("text/*")) {
            String s = (String)p.getContent();
            textIsHtml = p.isMimeType("text/html");
            return s;
        }

        if (p.isMimeType("multipart/alternative")) {
            // prefer html text over plain text
            Multipart mp = (Multipart)p.getContent();
            String text = null;
            for (int i = 0; i < mp.getCount(); i++) {
                Part bp = mp.getBodyPart(i);
                if (bp.isMimeType("text/plain")) {
                    if (text == null)
                        text = getText(bp);
                    continue;
                } else if (bp.isMimeType("text/html")) {
                    String s = getText(bp);
                    if (s != null)
                        return s;
                } else {
                    return getText(bp);
                }
            }
            return text;
        } else if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart)p.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                String s = getText(mp.getBodyPart(i));
                if (s != null)
                    return s;
            }
        }

        return null;
    }

(P.S. I am not sure this answer now useful to you but posted for the future reference if in case anyone is facing the same issue).