将内容类型从text / plain转换为带附件的电子邮件中的text / html

时间:2014-06-27 15:36:38

标签: java javamail content-type mime email-attachments

我正在尝试显示从服务器获取的电子邮件。在让您了解我的问题之前,请先查看我的代码:

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;
}

当电子邮件没有任何附件时,此代码可以正常工作。我收到了以html格式化的emailContent,因此可以毫不费力地阅读 我的问题是,一旦电子邮件包含附件文件,就不会显示任何内容 我发现这是因为内容类型,当使用简单邮件发送“text / html”时发送带附件的邮件时,“text / plain”。 所以我改变了我的条件以考虑内容类型,但显示的结果是...... uh..just原始文本
我甚至计划使用代码bodyPart2.setHeader("Content-Type", "text/html");将内容类型强制为“text / html”,但最终会出现异常。 有任何线索,为什么带附件的电子邮件的内容类型必须是“text / plain”?我已经用Google搜索了,但没有重要答案 我该怎么改呢? 非常感谢。

2 个答案:

答案 0 :(得分:0)

内容是text / plain还是text / html与邮件是否附件无关。

在某些情况下,邮件将包含包含text / plain和text / html部分的multipart / alternative内容。在这种情况下,您可以选择text / html部分。 This example code in the JavaMail FAQ可能有帮助。

如果邮件只有文字/简单部分,则由您决定格式化并显示它,但您认为最好。

答案 1 :(得分:0)

我用Daniel提出的解决方案解决了,尝试一下:

 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();
        }