This tutorial provides a sample spring MVC application that allows user sending an e-mail message.

In this tutorial, you are supposed to familiar with Java EE development as well as developing Spring MVC-based applications.

Spring Framework’s Support for E-mail

Based on JavaMail, Spring framework provides high-level abstraction API which greatly simplifies e-mail sending process. Let’s take a brief look at this API in the following class diagram:

To send e-mail messages, we can use an implementation of interface MailSender – the JavaMailSenderImpl class which is built upon on JavaMail. It’s convenient to configure this implementation as a bean in Spring’s context:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.mailgun.org" />
    <property name="username" value="postmaster@verwandlung.org" />
    <property name="password" value="" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>

Dependencies(pom.xml)

<!-- Spring -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>

<!-- Mail Service -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.5.2</version>
</dependency>
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.5.2</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>

The Mail Template

File Name: verifyEmail.vm

File Location: classpath: /mails/verifyEmail.vm (You can change this in configuration file)

<div style="padding:0;margin:0;background:#e9e9e9;font-family:'Segoe UI', 'Microsoft YaHei'">
<table width="625" style="background:#e9e9e9" cellspacing="0" cellpadding="0" border="0">
    <tbody>
        <tr>
            <td>
                <div style="color:#1b1b1b;background:#fff;border:1px solid #aaa;border-radius:5px;margin:15px;">
                    <table cellspacing="0" cellpadding="0" border="0">
                        <tbody>
                            <tr>
                                <td style="padding:15px 15px 0 15px;background:#fff;border-radius:4px 4px 0 0;">
                                    <div>
                                        <img src="http://verwandlung.org/assets/img/logo.png" alt="Testzilla" height="60" width="250">
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td style="padding:15px; background:#fff; border-radius:0 0 4px 4px;font-size:12px;">
                                    Hi ${username}, <br />
                                    There's just one step left to create your Verwandlung Online Judge account. <br /><br />
                                    To access your account and be eligible to receive testing projects, we need you to confirm your email address. <br />
                                    <a href="http://www.verwandlung.org/account/verifyEmail?email=${email}amp;amp;code=${code}">Click here to confirm your email address</a>. <br /><br />
                                    Thank you, <br />
                                    The Verwandlung Online Judge Team. <br /><br />
                                    <div style="border-top:3px solid #eee;color:#999;font-size:11px;line-height:1.2">
                                        <br>Powered by <a href="http://verwandlung.org" target="_blank" style="color: #005399;text-decoration: none;">Testzilla</a>. All rights reserved.<br>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </td>
        </tr>
    </tbody>
</table>
</div>

The Configuration of Spring MVC(dispatcher-servlet.xml)

<context:annotation-config />
<context:component-scan base-package="org.verwandlung.voj.web" />
<!-- Mail Service -->
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
    <!-- The path of mail templates -->
    <property name="resourceLoaderPath" value="classpath:/mails" />
    <property name="preferFileSystemAccess" value="false" />
</bean>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.mailgun.org" />
    <property name="username" value="postmaster@verwandlung.org" />
    <property name="password" value="" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>
<bean id="vojMailSender"
    class="org.verwandlung.voj.web.util.MailSender">
</bean>

Create Mail Sender Class

package org.verwandlung.voj.web.util;

import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

@Component
public class MailSender {
    @Autowired
    public MailSender(VelocityEngine velocityEngine, JavaMailSender mailSender) {
        this.velocityEngine = velocityEngine;
        this.mailSender = mailSender;
    }

    public String getMailContent(String templateLocation, Map<String, Object&gt; model) {
        return VelocityEngineUtils.
                mergeTemplateIntoString(velocityEngine, templateLocation, defaultEncoding, model);
    }

    public void sendMail(final String recipient, final String subject, final String body) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(recipient);
                message.setFrom("noreply@verwandlung.org");
                message.setSubject(subject);
                message.setText(body, true);
            }
        };
        mailSender.send(preparator);
        logger.info(String.format("An Email{Recipient: %s, Subject: %s} has been sent.",
                    new Object[] {recipient, subject}));
    }

    private final VelocityEngine velocityEngine;

    private final JavaMailSender mailSender;

    private final String defaultEncoding = "UTF-8"; 

    private Logger logger = LogManager.getLogger(MailSender.class);
}

How to Use it?

package org.verwandlung.voj.web.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.verwandlung.voj.web.util.MailSender;

@Service
@Transactional
public class UserService {
    public void sendActivationMail(String username, String email, String code) {
        String templatePath = "/verifyEmail.vm";
        Map<String, Object&gt; model = new HashMap<String, Object&gt;();
        model.put("username", username);
        model.put("email", email);
        model.put("code", code);

        String subject = "Activate Your Account";
        String body = mailSender.getMailContent(templatePath, model);
        mailSender.sendMail(email, subject, body);
    }

    @Autowired
    @Qualifier("vojMailSender")
    private MailSender mailSender;
}

The Disqus comment system is loading ...
If the message does not appear, please check your Disqus configuration.