Spring-Boot-摸索之路-4:Jetbrick-template生成邮件模版

接上篇博客Authenticate-user-by-Email

Maven导入Jetx依赖

1
2
3
4
5
<dependency>
<groupId>com.github.subchen</groupId>
<artifactId>jetbrick-template</artifactId>
<version>2.1.10</version>
</dependency>

类路径下创建后缀为jetx的文件

模版中的代码用HTML5的格式写就行。

Test.jetx

⚠️注意!!! jetx文件需要把邮件内容放在div标签中,不需要加其他HTML的元素。

1
2
3
4
5
6
7
8
9
10
11
<div>
<p>Dear <b>${username}</b>, 欢迎加入!</p>
<p>这是一封测试邮件</p>
<p>这里测试链接 ${url}</p>
<p>这里测试字符串 ${string}</p>
<p></p>
<p></p>
<p>-----------------------</p>
<p></p>
<p>(这是Jetx引擎的模版,请勿回复)</p>
</div>

MailUtil类中写方法

  • 配置JetEngine

    1
    2
    JetEngine engine = JetEngine.create();
    JetTemplate template = engine.getTemplate("/templates/JetxTemplates/Test.jetx");
  • 替换变量

    1
    2
    3
    4
    Map<String, Object> context = new HashMap<String, Object>();
    context.put("username", "User");
    context.put("string", "this is string");
    context.put("url", "<a href='http://www.baidu.com<'>http://www.baidu.com</a>");
  • 调用OhMyEmail中的Send()发送邮件

    1
    2
    3
    4
    5
    6
    7
    OhMyEmail.subject("这是一封测试Jetx模版的邮件")
    .from("Allwayz")
    .to(TO_EMAIL)
    .html(output)
    .send();
    Assert.assertTrue(true);
    System.out.println("Send...");

完整的发送类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
*
* @param string
* @param email
* @param user
* @throws SendMailException
*/
public static void sendTestEmail(String email, String string, String user)
throws SendMailException
{
JetEngine engine = JetEngine.create();
JetTemplate template = engine.getTemplate("/templates/JetxTemplates/test.jetx");

Map<String, Object> context = new HashMap<String, Object>();
context.put("username", user);
context.put("string", string);
context.put("url", "<a href='http://www.baidu.com<'>http://www.baidu.com</a>");

StringWriter writer = new StringWriter();
template.render(context, writer);
String output = writer.toString();
System.out.println(output);

OhMyEmail.subject("Welcome to FreeSeed")
.from("Allwayz")
.to(email)
.html(output)
.send();
Assert.assertTrue(true);
System.out.println("Send Success...");
}

测试类

1
2
3
4
5
6
7
@Test
public void testEmail() throws SendMailException{
String email = "xxxxxxxx@gamil.com";
String username = "User";
String string = "this is a String"
MailUtil.sendTestEmail(email,string,username);
}

Reference

JetBrick-Template-2x Documentation

JetBrick-Template Github源码

Allwayz