Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Rythm Engine for Email notification

DZone's Guide to

Rythm Engine for Email notification

· DevOps Zone
Free Resource

The DevOps Zone is brought to you in partnership with Sonatype Nexus. The Nexus Suite helps scale your DevOps delivery with continuous component intelligence integrated into development tools, including Eclipse, IntelliJ, Jenkins, Bamboo, SonarQube and more. Schedule a demo today

This article will discuss how to use Rythm as a template engine in sending email notifications.

Email, as a form of notification, that would alert us to be informed of events such as registration, newsletter, daily feeds, and social media update as well as system status.

Using an available open source application like Rythm will enable us to send an email with an html template easily.

Let’s first create an email content using html having Student information inside the table.

Below is the snippet of our html template (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>


Now, let’s go into some important details.

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

The above code snippet tells that our template would accept two arguments as java object (Student and String). It is important for you to include the fully qualified object name in order for the rhythm engine to discover your java object. (i.e com.sample.Student student).

[Accessing values from Student object]

I’ve created an html table to display the student information.

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

We can access the values from student object using the getter methods we’ve created preceded by @ sign (i.e @student.getId()).


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

The code snippet above shows how to display the value of note variable preceded by @ sign which will be shown at the bottom part of the email content.

Now, let's proceed in coding.

Below is the Student class.

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

And here is the main class

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

}

Let's discuss some lines above.

        /**
             * 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.

The DevOps Zone is brought to you in partnership with Sonatype Nexus. Use the Nexus Suite to automate your software supply chain and ensure you're using the highest quality open source components at every step of the development lifecycle. Get Nexus today

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}