我尝试实现java邮件api来读取消息正文并将其存储到文本文件中(如果它包含内容)。
我可以阅读消息正文,但它带有一些 html 元素。
我添加了以下我使用过的代码。
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("hostname", "username", "password");
String result = null;
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
javax.mail.Message messages[]=inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
for(Message message:messages) {
System.out.println(Jsoup.parse(message).text());
}
如何删除检索到的消息中的这些 html 元素?
请任何人帮我解决这个问题。
最佳答案
要删除邮件中的所有 HTML 标记,请使用 jsoups text()
方法。
示例代码
String htmlString = "<div class=\"WordSection1\"> <p class=\"MsoNormal\">Hi<br> <br> <br> <br> Data is written in this mail.<br> <br> <br> <br> <o:p></o:p></p> </div>";
System.out.println(Jsoup.parse(htmlString).text());
输出
Hi Data is written in this mail.
如果特定元素应导致类似于呈现的 HTML 源的换行符,您可以添加换行符,然后添加 avoid pretty printing它,当你 jsoups' clean
method .
prettyPrint
If disabled, the HTML output methods will not re-format the output, and the output will generally look like the input.
示例代码
String htmlString = "<div class=\"WordSection1\"> <p class=\"MsoNormal\">Hi<br> <br> <br> <br> Data is written in this mail.<br> <br> <br> <br> <o:p></o:p></p> </div>";
htmlString = htmlString.replaceAll("<br>", System.getProperty("line.separator") + "<br>"); // do replacements for all tags that should result in line-breaks
Document.OutputSettings settings = new OutputSettings();
settings.prettyPrint(false); // to keep line-breaks
String cleanedSource = Jsoup.clean(htmlString, "", Whitelist.none(), settings);
System.out.println(cleanedSource);
输出
Hi
Data is written in this mail.
[... four more empty lines]
关于java - 如何删除这些 html 元素,同时保留格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40232246/