Статьи

Rythm Engine для уведомлений по электронной почте

В этой статье мы обсудим, как использовать  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 (Student и String). Для вас важно включить полное имя объекта, чтобы ритм-движок обнаружил ваш Java-объект. (т.е. com.sample. Студент студент ).

[Доступ к значениям из объекта Student]

Я создал 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>

Мы можем получить доступ к значениям из объекта student с помощью созданных нами методов получения, перед которыми стоит знак @ ( т.е. @ student.getId () ).

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

Приведенный выше фрагмент кода показывает, как отобразить значение переменной примечания, которому предшествует знак @, который будет отображаться в нижней части содержимого электронной почты.

Теперь перейдем к кодированию.

Ниже находится студенческий класс.

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);

and below is the 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>

We’ve now successfully created our email notifications using rythm.