我正在使用java邮件发送html内容来创建html内容。
这是我得到的:
String format = "
<div style=\"font: 100% Verdana, Arial, Helvetica, sans-serif;
background: #eee;
margin: 0;
padding: 20px 0 20px 0;
text-align: center;
color: #000000;\">"
+ "
<div style=\"width:46em;
background: #FFFFFF;
margin: 0 auto;
text-align: left; \">"
我还想使用 bootstreap 或任何其他想要包含内联 css 的 css 文件。
如何减少代码以避免使用内联 CSS?
最佳答案
您可以使用Apache Velocity .
你可以这样做:
你的文件.html
<h1 style="color: #00">$entity.header</h1>
MyOwnEntity.java
public class MyOwnEntity{
private String header;
public MyOwnEntity(String header){
this.header = header;
}
public getHeader(){
return header;
}}
TemplateLoader.java
public class TemplateLoader {
public static <ENTITY> String loadFilledTemplate(ENTITY entity, String templatePath) throws IOException {
final Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(p);
final VelocityContext context = new VelocityContext();
context.put("entity", entity);
final Template template = Velocity.getTemplate(templatePath);
try (StringWriter writer = new StringWriter()) {
template.merge(context, writer);
return writer.toString();
}
}}
在你的类(class)
String format = TemplateLoader.loadFilledTemplate(new MyOwnEntity("custom"), "yourfile.html");
关于java - 如何为 Java Mail 构建 HTML 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28234095/