简体   繁体   English

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

[英]Convert content-type from text/plain to text/html in an email with attachment

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.我得到了电子邮件内容,格式为 html,因此可以轻松阅读。
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.我发现这是因为内容类型,当使用简单邮件发送带有附件的“文本/html”时,它是“文本/纯文本”。 So I changed my condition to take in account that content-type, but the result displayed is..uh..just raw text .所以我改变了我的条件以考虑到内容类型,但显示的结果是..uh..just raw text
I even planned to force the content-type to "text/html" with the code bodyPart2.setHeader("Content-Type", "text/html");我什至计划使用代码bodyPart2.setHeader("Content-Type", "text/html");强制内容类型为“text/html” 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.非常感谢。

Whether the content is text/plain or text/html has nothing to do with whether or not the message has attachments.内容是 text/plain 还是 text/html 与邮件是否有附件无关。

In some cases, messages will have a multipart/alternative content that contains both text/plain and text/html parts.在某些情况下,消息将具有包含 text/plain 和 text/html 部分的 multipart/alternative 内容。 In that case you can choose the text/html part.在这种情况下,您可以选择 text/html 部分。 This example code in the JavaMail FAQ might help. JavaMail FAQ 中的这个示例代码可能会有所帮助。

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.如果消息只有文本/纯文本部分,则由您来设置格式并以您认为最好的方式显示它。

I solved with solution proposed by Daniel , try it: 我用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();
        }

I solved with solution proposed by Daniel , try it:我用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();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Jersey客户端将内容类型标题设置为text / plain - Jersey Client set content-type header as text/plain Spring MVC 3返回内容类型:text / plain - Spring MVC 3 Return Content-Type: text/plain Jersey:阅读内容类型:简单/文本响应为XML - Jersey: Reading Content-Type:plain/text response as XML Firefox甚至尝试使用Content-Type解析XML:text / plain - Firefox tries to parse XML even with Content-Type: text/plain Spring Data Rest自定义控制器,带内容类型:“text / plain” - Spring Data Rest Custom Controller With with content-Type:“text/plain” 使用EWS java API将Content-Type设置为text / plain - Set Content-Type as text/plain using EWS java API 无法从Elastic 6.0获取数据:“错误”:“不支持Content-Type标头[文本/纯文本]”,“状态”:406 - Cannot get data from Elastic 6.0: “error”:”Content-Type header [text/plain] is not supported”,”status”:406 将格式化的电子邮件(HTML)转换为纯文本? - Convert formatted email (HTML) to plain Text? 通过爬取内容类型不是text/html的URL - Getting the URL by crawling whose content-type is not text/html JENA:端点返回内容类型:text/html - JENA: Endpoint returned Content-Type: text/html
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM