当type为text / html时,阅读电子邮件内容;字符集= ISO-8859-1

时间:2017-05-19 09:50:23

标签: java email javamail

我正在阅读来自特定文件夹的未读电子邮件。邮件内容类型为 text / html; charset = iso-8859-1 。如何将内容作为字符串获取?当我做一个toString我得到这样的东西com.sun.mail.util.QPDecoderStream@4461c7e3

  public Message[] fetchMessages(String host, String user, String password,String folder, boolean read) throws IOException {
            try {
                Properties properties = new Properties();
                properties.put("mail.store.protocol", "imaps");

                Session emailSession = Session.getDefaultInstance(properties);
                Store store = emailSession.getStore();
                store.connect(host, user, password);

                Folder folderToRead = store.getFolder(folder);
                folderToRead.open(Folder.READ_WRITE);
                Flags seen = new Flags(Flags.Flag.SEEN);
                FlagTerm unseenFlagTerm = new FlagTerm(seen, read);
                Message messages[] = folderToRead.search(unseenFlagTerm);
                System.out.println(messages.length);
                for(Message message : messages){
                    System.out.println(getMessageContent(message));
                }
    }
public getMessageContent(Message message){
        String result = "";
        if (message.isMimeType("text/html")) {
           // My message type is coming as text/html
            result = message.getContent().toString();
        }
        else if (message.isMimeType("text/plain")) {
            result = message.getContent().toString();
        } 
        return result;

}

1 个答案:

答案 0 :(得分:0)

text / plain是一种未知类型,并且作为输入流出现。这对我有用

private static String getTextFromMessage(Message message) throws IOException, MessagingException {
        String result = "";
       if (message.isMimeType("text/plain")) {
            result = message.getContent().toString();
        } else if (message.isMimeType("multipart/*")) {
            MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
            result = getTextFromMimeMultipart(mimeMultipart);
        }
        else{
             StringWriter writer = new StringWriter();
             IOUtils.copy(message.getInputStream(), writer, "UTF-8");
             result = writer.toString();
        }
        return result;
    }