如何使java字符串加粗和着色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19375979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:34:28  来源:igfitidea点击:

how to make java string bold and colored

javaemailhtml-email

提问by Rohhit

I am developing email application using java. I have a string as follows :

我正在使用 java 开发电子邮件应用程序。我有一个字符串如下:

String msg= "College Email \nHello"+" "+name+"\n"+"You are selected As 'Admin'.\n Please use Given username and password for login\n \Username:"+" "+username+" "+"Password:"+" "+password+"";

I want send this string as email message. and i want to "BOLDand color" username and password(I want to show this message in inbox i.e on browser). how can i embed HTML tags to do this ? OR is there any simple way to do this without using HTML tags ?

我想将此字符串作为电子邮件发送。我想“粗体和彩色”用户名和密码(我想在收件箱中显示此消息,即在浏览器上)。我怎样才能嵌入 HTML 标签来做到这一点?或者有什么简单的方法可以在不使用 HTML 标签的情况下做到这一点?

Can any one correct above string (msg) OR provide any link or code to fix this problem ?

任何人都可以更正上述字符串 (msg) 或提供任何链接或代码来解决此问题吗?

thank you.

谢谢你。

采纳答案by Petr Mensik

Just type the tags into your message like String msg = "<strong>Hello World!</strong>and send it as a HTML message, you only need to set type of the content via MimeMessage#setContent()method like

只需在您的消息中键入标签String msg = "<strong>Hello World!</strong>并将其作为 HTML 消息发送,您只需要通过MimeMessage#setContent()类似的方法设置内容的类型

message.setContent(msg, "text/html; charset=utf-8");`

回答by yamafontes

If you want to do it the old school, vanilla java way you can use the org.w3c.dom.DocumentAPI to get the work done.

如果你想用老式的、vanilla java 的方式来做,你可以使用org.w3c.dom.DocumentAPI 来完成工作。

It has a bunch of useful methods for creating and manipulating elements such as createElement, createAttribute, etc. to do what you want.

它用于创建和操作元件,如一堆有用的方法createElementcreateAttribute等等。做你想做什么。

http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Document.html

http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Document.html

回答by Ashwin Parmar

As per the Javadoc, the MimeMessage#setText()sets a default mime type of text/plain, while you need text/html. Rather use MimeMessage#setContent()instead.

根据JavadocMimeMessage#setText()设置默认的 MIME 类型text/plain,而您需要 text/html。而是使用MimeMessage#setContent()代替。

String someHtmlMessage = "Hello this is test message <b style='color:blue;'>bold color</b>";

message.setContent(someHtmlMessage, "text/html; charset=utf-8");

Note that the HTML should not contain the <html>, <head> or <body>. Gmail will ignore it. See also CSS support in mail clients.

请注意,HTML 不应包含<html>, <head> or <body>. Gmail 会忽略它。另请参阅邮件客户端中的 CSS 支持。