0

I'm trying to display email messages gotten from the server. Prior to letting you know my issue, take a look at my code:

public FileMailExtended getSingleMessage(Integer fileMailId) throws MailSystemException, IOException,
        MessagingException, BOServiceException {
    FileMail email = retrieve(fileMailId.intValue());

    MailerScopeDef scope = email.getType();
    boolean outbound = email.getDirection() == EmailConstants.DIRECTION_SENT;
    Long uId = Long.valueOf(email.getUId());

    String folder = null;
    if (outbound) {
        folder = ConfigurationService.getSentFolder(scope);
    } else {
        folder = ConfigurationService.getReadFolder(scope);
    }

    FileMailConfig fileMailConfig = getFileMailConfig(folder);
    long uidValidity = 0;
    if (fileMailConfig != null) {
        uidValidity = fileMailConfig.getVersionId();
    }

    ImapFolderManager ifm;
    if (outbound) {
        ifm = ((ImapSender) ConfigurationService.getMailSender(scope)).getImapFolderMger();
    } else {
        ifm = ConfigurationService.getImapFolderManagerReader(scope);
    }

    FileMailExtended emailExtended = new FileMailExtended();
    mapFileMailToFileMailExtended(email, emailExtended);
    try {
        IMAPMessage message = (IMAPMessage) ifm.getMessage(uId, uidValidity);
        if (message == null) {
            LOGGER.error("Could not read message with uId:" + uId + " from the server.");
            return null;
        }

        InternetAddress intAdress = (InternetAddress) message.getSender();
        String unicodeString = intAdress.toUnicodeString().replace("\"", "");
        emailExtended.setFrom(unicodeString);
        emailExtended.setTo(appendAddresses(message.getRecipients(RecipientType.TO)));
        emailExtended.setCc(appendAddresses(message.getRecipients(RecipientType.CC)));
        emailExtended.setCci(appendAddresses(message.getRecipients(RecipientType.BCC)));
        emailExtended.setSubject(message.getSubject());

        String content = "";

        if (message.getContent() instanceof String) {
            content += (String) message.getContent();
        } else if (message.getContent() instanceof Multipart) {
            Multipart multipart = (Multipart) message.getContent();
            StringBuffer buf = new StringBuffer();
            for (int x = 0; x < multipart.getCount(); x++) {
                BodyPart bodyPart = multipart.getBodyPart(x);
                if (bodyPart == null || bodyPart.getContentType() == null) {
                    continue;
                }
                if (bodyPart.isMimeType(TEXT_HTML)) {
                    buf.append((String) bodyPart.getContent());
                } else if (bodyPart.getContent() instanceof Multipart) {
                    Multipart multipart2 = (Multipart) bodyPart.getContent();
                    for (int xx = 0; xx < multipart2.getCount(); xx++) {
                        BodyPart bodyPart2 = multipart2.getBodyPart(xx);
                        if (bodyPart2 != null && bodyPart2.isMimeType("text/html") {
                            buf.append((String) bodyPart2.getContent());
                        }
                    }
                }
            }
            content = buf.toString();
        }
        emailExtended.setContent(content);

        if (message.getContent() instanceof Multipart) {
            Multipart multipart = (Multipart) message.getContent();
            for (int i = 0; i < multipart.getCount(); i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                    // dealing with attachments only
                    continue;
                }
                emailExtended.addAttachmentNames(bodyPart.getFileName());
            }
        }

    } finally {
        closeFolderManager(ifm);
    }

    return emailExtended;
}

This code works fine when the email doesn't have any attachments. I get the emailContent, formatted in html, thus readable without efforts.
My problem is, once the email contains an attachment file, nothing is displayed.
I discovered that it was because of the content-type, which was "text/plain" when sending a message with attachments when "text/html" with simple mail. So I changed my condition to take in account that content-type, but the result displayed is..uh..just raw text.
I even planned to force the content-type to "text/html" with the code bodyPart2.setHeader("Content-Type", "text/html"); , but it ended up with an exception. Any clue why the content-type of email with attachments has to be "text/plain"? i already googled it, but no significant answers.
How can I change it?
Many thanks.

user3783672
  • 1
  • 1
  • 3

2 Answers2

0

Whether the content is text/plain or text/html has nothing to do with whether or not the message has attachments.

In some cases, messages will have a multipart/alternative content that contains both text/plain and text/html parts. In that case you can choose the text/html part. This example code in the JavaMail FAQ might help.

If the message has only a text/plain part, it's up to you to format it and display it however you think would be best.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40
0

I solved with solution proposed by Daniel, try it:

 public static String ConvertTextPlanToHTML(String s) {
            StringBuilder builder = new StringBuilder();
            boolean previousWasASpace = false;
            for( char c : s.toCharArray() ) {
                if( c == ' ' ) {
                    if( previousWasASpace ) {
                        builder.append("&nbsp;");
                        previousWasASpace = false;
                        continue;
                    }
                    previousWasASpace = true;
                } else {
                    previousWasASpace = false;
                }
                switch(c) {
                    case '<': builder.append("&lt;"); break;
                    case '>': builder.append("&gt;"); break;
                    case '&': builder.append("&amp;"); break;
                    case '"': builder.append("&quot;"); break;
                    case '\n': builder.append("<br>"); break;
                    // We need Tab support here, because we print StackTraces as HTML
                    case '\t': builder.append("&nbsp; &nbsp; &nbsp;"); break;  
                    default:
                        if( c < 128 ) {
                            builder.append(c);
                        } else {
                            builder.append("&#").append((int)c).append(";");
                        }    
                }
            }
            return builder.toString();
        }
Marco Ferrara
  • 516
  • 1
  • 8
  • 26