用于电子邮件通知的Rythm引擎


本文将讨论如何使用Rythm作为发送电子邮件通知的模板引擎。

电子邮件作为通知的一种形式,可以提醒我们获知注册、时事通讯、每日馈送、社交媒体更新以及系统状态等事件。

使用像Rythm这样可用的开源应用程序将使我们能够轻松地发送带有html模板的电子邮件。

让我们首先使用html创建一个电子邮件内容,其中包含表中的学生信息。

下面是我们的html模板(content.html)的片段。

 @args(){
com.sample.Student student
String message
}
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title></title>
    <style>
        table {
            font-family: Segoe UI, Verdana, Arial, helvetica, sans-serif;
            font-size: 14px;
            background-color: #FFFFFF;
        }

        th {
            margin-left: 5px;
            margin-right: 5px;
            text-align: left;
        }

        td {
            margin-left: 5px;
            margin-right: 5px;
            background-color: #E5E5E5;
        }
    </style>
</head>
<body>
<table style="width:100%">
    <tr>
        <th colspan="2" style="color: white" bgcolor="#FF8C00">Student Information</th>
    </tr>

    <tr>
        <td>Student ID</td>
        <td>@student.getId()</td>
    </tr>
    <tr>
        <td>Name</td>
        <td>@student.getName()</td>
    </tr>
  <tr>
        <td>Age</td>
        <td>@student.getAge</td>
    </tr>
    <tr>
        <td>Course</td>
        <td>@student.getCourse()</td>
    </tr>
</table>
<br>
<p style="font-style: italic">@note</p>
</body>
</html>


现在,让我们来了解一些重要的细节。

@args(){
com.sample.Student student
String note
}

上面的代码片段告诉我们,我们的模板将接受两个参数作为java对象(学生和字符串)。为了让节奏引擎发现您的Java对象,包括完全限定的对象名称是很重要的。(即com.sample.学生)。

[从学生对象访问值]

我已经创建了一个html表来显示学生信息。

<table style="width:100%">
    <tr>
        <th colspan="2" style="color: white" bgcolor="#FF8C00">Student Information</th>
    </tr>

    <tr>
        <td>Student ID</td>
        <td>@student.getId()</td>
    </tr>
    <tr>
        <td>Name</td>
        <td>@student.getName()</td>
    </tr>
  <tr>
        <td>Age</td>
        <td>@student.getAge()</td>
    </tr>
    <tr>
        <td>Course</td>
        <td>@student.getCourse()</td>
    </tr>
</table>

我们可以使用创建的getter方法访问学生对象中的值,该方法前面带有@sign(即@Student.getId())。


<p style="font-style: italic">@note</p>

上面的代码片段显示了如何在电子邮件内容的底部显示前面带有@Sign的备注变量的值。

现在,让我们继续编码。

下面是学生班。

package com.sample;

public class Student {

    private int id;
    private String name;
    private int age;
    private String course;

    public Student(int id, String name, int age, String course) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.course = course;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getCourse() {
        return course;
    }
}

这是主课

package com.sample;


import org.rythmengine.RythmEngine;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;

/**
 * Created by FaustineP™ on 1/5/2015.
 */
public class Main {

    public static void main(String args[]) {
        Session session = setGOOGLESMTPConfig();
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("sender@gmail.com"));
            message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@gmail.com"));
            String subject = String.format("[%s]", "Rythm Engine Template Email");
            message.setSubject(subject);
            RythmEngine rythmEngine = new RythmEngine();
            Student student = new Student(2061435412, "Student Name", 25, "BS Computer Science");
            String note = "* This is a system generated email do not reply";
            File template = new File(String.valueOf(Main.class.getClassLoader().getResource("content.html").getFile()));
            String bodyContent = rythmEngine.render(template, student, note);
            message.setContent(bodyContent, "text/html; charset=utf-8");
            javax.mail.Transport.send(message);
            System.out.println("[Message sent!]");
        } catch (MessagingException e) {
            System.out.println(e);
        }
    }

    private static Session setGOOGLESMTPConfig() {
        final Properties properties = System.getProperties();
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.socketFactory.port", String.valueOf("465"));
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        return Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("USERNAME", "PASSWORD");
            }
        });
    }

}

让我们讨论一下上面的几行。

        /**
             * Instantiate RythmEngine object
             */
            RythmEngine rythmEngine = new RythmEngine();
            /**
             * Instantiate Student object and assign values to its corresponding variables 
             */
            Student student = new Student(2012, "Student Name", 25, "BS Computer Science");
            /**
             * String object as a note that will be shown at the bottom part of email
             */
            String note = "* This is a system generated email do not reply";
            /**
             * The location of HTML template file we've created (content.html)
             */
            File template = new File(String.valueOf(Main.class.getClassLoader().getResource("content.html").getFile()));
            /**
             * We can now render our object to the HTML content of our email
             */
            String bodyContent = rythmEngine.render(template, student, note);

下面是pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sample</groupId>
    <artifactId>rythm-email</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.rythmengine</groupId>
            <artifactId>rythm-engine</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.codemonkey.simplejavamail</groupId>
            <artifactId>simple-java-mail</artifactId>
            <version>2.1</version>
        </dependency>
    </dependencies>
</project>

我们现在已经成功地使用rythm创建了电子邮件通知。