Extract content and attachments from an Message use Javax mail (with embedded message EML, MSG)


The main part in a javax message is the content. The content can be any Java object representing the mail content, like a plain text (String) or raw image data or even a multiple part object. A multiple part content a message’s content consists of more than a single item. A multiple part object is a container which holds one ore more BodyPart objects. These BodyParts, like a message, have a content and a content type (in fact, both message and BodyPart implement the same interface Part which carries these properties).

Beside plain content, A BodyPart can contain another Multipart or even another Message, a so called nested message (e.g. a forwarded message, called embedded message) with content type ‘message/rfc822’.

image1-6

As you can see, the structure of a message can be rather heterogeneous, a tree with nodes of different types. The following picture illustrates the tree structure for a sample message.

public String downloadContentAndAttachments(
        final String outDir,
        final EMSMessage emsMessage)
    {
        String folder = null;

        try
        {
            if (emsMessage != null)
            {
                log.info("Start downloading content ...");
                final String subject = emsMessage.getSubject();
                if (subject.equalsIgnoreCase("Adressmutation"))
                {
                    System.out.println(subject);
                }
                String from = "";
                if (emsMessage.getFrom() != null)
                {
                    for (final String sender : emsMessage.getFrom())
                    {
                        from += sender.toString() + Constant.CHAR_SEMICOLON;
                    }
                }
                String to = "";
                if (emsMessage.getRecipients() != null)
                {
                    for (final String recipian : emsMessage.getRecipients())
                    {
                        to += recipian.toString() + Constant.CHAR_SEMICOLON;
                    }
                }
                folder = FileUtils.standardizeFileName(subject, true);
                if (folder != null)
                {
                    final String tempDir = outDir + File.separator + folder;
                    final StringBuilder htmlSB = new StringBuilder();
                    final StringBuilder textSB = new StringBuilder();
                    int isHTML = 1;
                    final Message message = emsMessage.getMessage();
                    final Object content = message.getContent();
                    if (content instanceof String)
                    {
                        if (this.isHTMLContent((String) content))
                        {
                            final String partContent = content.toString();
                            if (partContent != null)
                            {
                                htmlSB.append(partContent);
                                isHTML = 1;
                            }
                        }
                        else
                        {
                            final String partContent = content.toString();
                            if (partContent != null)
                            {
                                textSB.append(partContent);
                                isHTML = 2;
                            }
                        }
                    }
                    else if (content instanceof MimeMultipart)
                    {

                        final Multipart multiPart = (Multipart) content;
                        isHTML = this.getContent(
                            tempDir,
                            multiPart,
                            htmlSB,
                            textSB,
                            emsMessage);
                    }
                    String contentHTMLFile = FileUtils
                        .decorateSavedAttachmentFile(
                            tempDir,
                            DCOConfiguration.DEFAULT_CONTENT_FILE
                                    + Constant.FILE_EXSTENSION_HTML).trim();
                    final StringBuilder sbContent = new StringBuilder();
                    String newLineDecorator = "
";
                    if (isHTML == 1)
                    {
                        sbContent.append("From: ").append(from)
                            .append(newLineDecorator).append("Subject: ")
                            .append(subject).append(newLineDecorator)
                            .append("To: ").append(to).append(newLineDecorator)
                            .append(newLineDecorator + newLineDecorator)
                            .append(htmlSB.toString());
                        FileUtils.saveStringToFile(
                            sbContent.toString(),
                            contentHTMLFile);
                    }
                    else if (isHTML == 2)
                    {
                        newLineDecorator = "\n";
                        sbContent.append("From: ").append(from)
                            .append(newLineDecorator).append("Subject: ")
                            .append(subject).append(newLineDecorator)
                            .append("To: ").append(to).append(newLineDecorator)
                            .append(newLineDecorator + newLineDecorator)
                            .append(textSB.toString());
                        contentHTMLFile = contentHTMLFile.replace(
                            Constant.FILE_EXSTENSION_HTML,
                            Constant.FILE_EXSTENSION_TXT);
                        FileUtils.saveStringToFile(
                            sbContent.toString(),
                            contentHTMLFile);
                    }
                    sbContent.setLength(0);
                    emsMessage.getAttachments().add(0, contentHTMLFile);
                    htmlSB.setLength(0);
                }
            }
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }

        return folder;
    }
private int getContent(
        final String outDir,
        final Multipart part,
        final StringBuilder htmlSB,
        final StringBuilder textSB,
        final EMSMessage emsMessage)
    {
        int ret = 1;

        if ((part != null) && (htmlSB != null) && (textSB != null))
        {
            try
            {
                for (int i = 0; i < part.getCount(); i++)
                {
                    final BodyPart bodyPart = part.getBodyPart(i);
                    if (bodyPart instanceof MimeBodyPart)
                    {
                        final MimeBodyPart body = (MimeBodyPart) bodyPart;
                        final Object content = body.getContent();
                        final String cType = body.getContentType();
                        final String name = this.getContentTypeName(cType);
                        if (content instanceof Multipart)
                        {
                            final Multipart mp = (Multipart) content;
                            ret = this.getContent(
                                outDir,
                                mp,
                                htmlSB,
                                textSB,
                                emsMessage);
                        }
                        else if ((content instanceof String)
                                && ((name == null) || name.isEmpty()))
                        {
                            if (this.isHTMLContent((String) content))
                            {
                                final String partContent = content.toString();
                                if (partContent != null)
                                {
                                    htmlSB.append(partContent);
                                    ret = 1;
                                }
                            }
                            else
                            {
                                final String partContent = content.toString();
                                if (partContent != null)
                                {
                                    textSB.append(partContent);
                                    ret = 2;
                                }
                            }
                        }
                        else if (content instanceof MimeMessage)
                        {
                            final MimeMessage embeddedMessage = (MimeMessage) content;
                            final String subject = embeddedMessage.getSubject();
                            if (emsMessage.getDegree() < 2)
                            {
                                log.info(" + "
                                        + subject
                                        + " : found at the first degree: It will be converted to message for latter processing");
                                final EMSMessage emsg = new EMSMessage(
                                    embeddedMessage, emsMessage);
                                ProcessorImpl.getInstance().addMessage(emsg);
                                emsMessage.setHasChild(true);
                            }
                            else
                            {
                                log.info(" + "
                                        + subject
                                        + " : found at the second degree: Download and leave it alone !");
                                try
                                {
                                    final String attachmentName = FileUtils
                                        .standardizeFileName(subject
                                                + Constant.FILE_EXSTENSION_EML);
                                    final String filePath = FileUtils
                                        .decorateSavedAttachmentFile(
                                            outDir,
                                            attachmentName).trim();
                                    FileUtils.saveMail2File(
                                        embeddedMessage,
                                        filePath);
                                    emsMessage.getAttachments().add(filePath);
                                }
                                catch (final Exception e)
                                {
                                    log.error("Failed to save embbed message in second degree message to EML");
                                }
                            }
                        }
                        else
                        {
                            String attachmentName = this.getFileName(body);
                            if ((attachmentName != null)
                                    && !attachmentName.isEmpty())
                            {
                                try
                                {
                                    attachmentName = FileUtils
                                        .standardizeFileName(attachmentName);
                                    final String filePath = FileUtils
                                        .decorateSavedAttachmentFile(
                                            outDir,
                                            attachmentName).trim();
                                    final File file = new File(filePath);
                                    if (!file.exists())
                                    {
                                        file.getParentFile().mkdirs();
                                    }
                                    log.info(" + " + attachmentName + "...");
                                    body.saveFile(filePath);
                                    if (filePath.toLowerCase().endsWith(
                                        Constant.FILE_EXSTENSION_MSG))
                                    {
                                        try
                                        {
                                            emsMessage.setHasChild(true);
                                            if (emsMessage.getDegree()  1))
                    {
                        if ("name".equalsIgnoreCase(split[0].trim()))
                        {
                            name = split[1].trim();
                            break;
                        }
                    }
                }
            }
        }

        return name;
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.