Home » Enterprise Java » spring » MVC » Sending Email With Spring MVC Example

About Yatin Batra

Yatin Batra
Yatin has graduated in Electronics & Telecommunication. During his studies, he has been involved with a large number of projects ranging from programming and software engineering to telecommunications analysis. He works as a software developer in the information technology sector where he is mainly involved with projects based on Java and J2EE technologies platform.

Sending Email With Spring MVC Example

Spring provides the first-class support for sending emails. It comes with the utility libraries which abstracts away the complexities of the underlying mailing system and provides a simple API to use in the application for sending emails. In this tutorial, we will show how to write a simple Web application for sending an email based on the Spring MVC framework and the JavaMail API.

Want to master Spring Framework ?

Subscribe to our newsletter and download the Spring Framework Cookbook right now!

In order to help you master the leading and innovative Java framework, we have compiled a kick-ass guide with all its major features and use cases! Besides studying them online you may download the eBook in PDF format!

 

1. Introduction

1.1 Spring Framework

  • Spring is an open-source framework created to address the complexity of an enterprise application development
  • One of the chief advantages of the Spring framework is its layered architecture, which allows developer to be selective about which of its components they can use while providing a cohesive framework for J2EE application development
  • Spring framework provides support and integration to various technologies for e.g.:
    • Support for Transaction Management
    • Support for interaction with the different databases
    • Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
    • Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
    • Support for REST style web services

1.2 Spring MVC Framework

Model-View-Controller (MVC) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:

  • Model (M): Model’s responsibility is to manage the application’s data, business logic, and the business rules. It is a POJO class which encapsulates the application data given by the controller
  • View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the JSP templates written with Java Standard Tag Library (JSTL)
  • Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In spring framework, the controller part is played by the Dispatcher Servlet
Fig. 1: Model View Controller (MVC) Overview

Fig. 1: Model View Controller (MVC) Overview

1.3 Spring Framework’s Support for Email

Spring Email support is built upon the JavaMail API which provides a high-level abstraction API for simplifying the email sending process. Let’s take a brief look at this API in the following class diagram.

Fig. 2: Spring Framework Email API Overview

Fig. 2: Spring Framework Email API Overview

To send the email messages, developers can use the implementation of the MailSender interface. This interface has the JavaMailSenderImpl class which is built upon on the JavaMail API and if often convenient to configure this implementation as a bean in the spring’s context.

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <!-- SMTP settings -->
    <property name="host" value="SMTP_HOST" />
    <property name="port" value="SMTP_PORT" />
    <property name="username" value="USER_NAME" />
    <property name="password" value="PASSWORD" />
 
    <property name="javaMailProperties">
        <!-- additional properties specific to JavaMail -->
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>

This spring’s bean holds the properties for the SMTP and the JavaMail that can be injected to a service class which needs to send an email. For e.g.:

mailSender.send(emailObj);

In this, the emailObj is an object of a type that implements the MailMessage interface (i.e. SimpleMailMessage class). Developers can construct the email object as follows:

SimpleMailMessage emailObj = new SimpleMailMessage();
emailObj.setTo(toAddress);
emailObj.setSubject(emailSubject);
emailObj.setText(emailBody);

That’s for a simple plain text email message. In case, if developers want to send an HTML email or attach files to an email, they can use the MimeMailMessage class with the help of MimeMessagePreparator and MimeMessageHelper classes. For e.g.:

mailSender.send(new MimeMessagePreparator() {
  public void prepare(MimeMessage mimeMessageObj) throws MessagingException {
    MimeMessageHelper messageObj = new MimeMessageHelper(mimeMessageObj, true, "UTF-8");
    messageObj.setFrom(fromEmail);
    messageObj.setTo(toEmail);
    messageObj.setSubject("Test File");
    messageObj.setText("See The Attached", true);
    messageObj.addAttachment("Template.doc", new File("Template.doc"));
  }
});

1.3.1 Spring JavaMail API

The following table summarizes the interfaces and classes provided in org.springframework.mail package for supporting the JavaMail API.

No.Description
1.MailSenderIt is the root interface which provides the basic functionality for sending simple emails.
2.JavaMailSenderIt is the subinterface of the MailSender which supports MIME messages. Mostly used with the MimeMessageHelper class for the creation of JavaMail MimeMessage. The Spring framework recommends MimeMessagePreparator mechanism for using this interface.
3.JavaMailSenderImplIt provides the implementation of JavaMailSender interface which supports JavaMail MimeMessage and Spring SimpleMailMessage.
4.SimpleMailMessageIt is used to create a simple email message including from, to, cc, subject and text messages.
5.MimeMessagePreparatorIt is a callback interface for the preparation of JavaMail MimeMessage.
6.MimeMessageHelperIt is the helper class for creating a MimeMessage which offers support for the inline elements such as images, attachments and HTML text contents.

Now, open up the Eclipse IDE and let’s see how to implement the code for sending emails in the spring framework!

2. Sending Email with Spring MVC Example

Here is a step by step guide for sending emails using the spring’s framework org.springframework.mail.javamail.JavaMailSender interface.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Application Structure

Fig. 3: Application Structure

2.3 Project Creation

This section will demonstrate on how to create a Java based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 4: Create Maven Project

Fig. 4: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 5: Project Details

Fig. 5: Project Details

Select the Maven Web App Archetype from the list of options and click Next.

Fig. 6: Archetype Selection

Fig. 6: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 7: Archetype Parameters

Fig. 7: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<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>SpringMvcEmail</groupId>
	<artifactId>SpringMvcEmail</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

We can start adding the dependencies that developers want like Spring MVC, Spring Email Support etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependency for the Spring and Spring Email framework. The rest dependencies will be automatically resolved by Maven, such as Spring Core, Spring Beans, Spring MVC etc. The updated file will have the following code:

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>SpringMvcEmail</groupId>
	<artifactId>SpringMvcEmail</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMvcEmail Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<!-- Servlet API Dependency -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
		</dependency>
		<!-- Spring Framework Dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<!-- All Mail Related Stuff + Much more -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<!-- Java Mail Dependency -->
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>javax.mail-api</artifactId>
			<version>1.5.5</version>
		</dependency>
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4.7</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 8: Java Package Creation

Fig. 8: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.spring.mvc.email.

Fig. 9: Java Package Name (com.jcg.spring.mvc.email)

Fig. 9: Java Package Name (com.jcg.spring.mvc.email)

Once the package is created in the application, we will need to create the controller class. Right-click on the newly created package: New -> Class.

Fig. 10: Java Class Creation

Fig. 10: Java Class Creation

A new pop window will open and enter the file name as EmailController. The controller class will be created inside the package: com.jcg.spring.mvc.email.

Fig. 11: Java Class (EmailController.java)

Fig. 11: Java Class (EmailController.java)

3.2.1 Implementation of Controller Class

It is a simple class where the @Controller annotation is used to specify this class as a spring controller and is responsible for handling the email form’s submission which is configured by the @RequestMapping annotation.

The second parameter of the sendEmail() method is annotated by @RequestParam annotation which maps the email form field: attachFileObj to a CommonsMultipartFile object that represents an upload file.

In the sendEmail() method, we are capturing the input fields from the email form (i.e. mailto, subject, and message) and send an email by invoking the send() method on the mailSenderObj object (which is automatically injected to this controller via the @Autowired annotation).

The send() method is passed with an anonymous class which implements the MimeMessagePreparator interface and implements the prepare() method. In the prepare() method we will construct the email message object with help of the MimeMessageHelper class and invoke its addAttachment() method to attach the upload file as an attachment to the email. This method reads the data of the upload file from the input stream which is returned by the attachFileObj object.

Finally, the controller redirects the user to a result page whose logical name is: success. Add the following code to it:

EmailController.java

package com.jcg.spring.mvc.email;

import java.io.IOException;
import java.io.InputStream;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class EmailController {

	static String emailToRecipient, emailSubject, emailMessage;
	static final String emailFromRecipient = "<!-- Source Email Address -->";

	static ModelAndView modelViewObj;

	@Autowired
	private JavaMailSender mailSenderObj;

	@RequestMapping(value = {"/", "emailForm"}, method = RequestMethod.GET)
	public ModelAndView showEmailForm(ModelMap model) {
		modelViewObj = new ModelAndView("emailForm");
		return  modelViewObj;		
	}

	// This Method Is Used To Prepare The Email Message And Send It To The Client
	@RequestMapping(value = "sendEmail", method = RequestMethod.POST)
	public ModelAndView sendEmailToClient(HttpServletRequest request, final @RequestParam CommonsMultipartFile attachFileObj) {

		// Reading Email Form Input Parameters		
		emailSubject = request.getParameter("subject");
		emailMessage = request.getParameter("message");
		emailToRecipient = request.getParameter("mailTo");

		// Logging The Email Form Parameters For Debugging Purpose
		System.out.println("\nReceipient?= " + emailToRecipient + ", Subject?= " + emailSubject + ", Message?= " + emailMessage + "\n");

		mailSenderObj.send(new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {

				MimeMessageHelper mimeMsgHelperObj = new MimeMessageHelper(mimeMessage, true, "UTF-8");				
				mimeMsgHelperObj.setTo(emailToRecipient);
				mimeMsgHelperObj.setFrom(emailFromRecipient);				
				mimeMsgHelperObj.setText(emailMessage);
				mimeMsgHelperObj.setSubject(emailSubject);

				// Determine If There Is An File Upload. If Yes, Attach It To The Client Email				
				if ((attachFileObj != null) && (attachFileObj.getSize() > 0) && (!attachFileObj.equals(""))) {
					System.out.println("\nAttachment Name?= " + attachFileObj.getOriginalFilename() + "\n");
					mimeMsgHelperObj.addAttachment(attachFileObj.getOriginalFilename(), new InputStreamSource() {					
						public InputStream getInputStream() throws IOException {
							return attachFileObj.getInputStream();
						}
					});
				} else {
					System.out.println("\nNo Attachment Is Selected By The User. Sending Text Email!\n");
				}
			}
		});
		System.out.println("\nMessage Send Successfully.... Hurrey!\n");

		modelViewObj = new ModelAndView("success","messageObj","Thank You! Your Email Has Been Sent!");
		return  modelViewObj;	
	}
}

Note:

  • If the user doesn’t pick up a file to be shared as an attachment, the attachFileObj will be empty and a plain text format email will be sent to the customer mailbox

3.3 Configuration Files

Let’s write all the configuration files involved in this application.

3.3.1 Spring Configuration File

To configure the spring framework, we need to implement a bean configuration file i.e. spring-servlet.xml which provides an interface between the basic Java class and the outside world. Right-click on SpringMVCRedirect/src/main/webapp/WEB-INF folder, New -> Other.

Fig. 12: XML File Creation

Fig. 12: XML File Creation

A new pop window will open and select the wizard as an XML file.

Fig. 13: Wizard Selection

Fig. 13: Wizard Selection

Again, a pop-up window will open. Verify the parent folder location as: SpringMvcEmail/src/main/webapp/WEB-INF and enter the file name as: spring-servlet.xml. Click Finish.

Fig. 14: spring-servlet.xml

Fig. 14: spring-servlet.xml

Once the XML file is created, we will add the following code to it:

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd               http://www.springframework.org/schema/context               http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <context:component-scan base-package="com.jcg.spring.mvc.email" />
    
    <!-- Spring Email Sender Bean Configuration -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.mail.yahoo.com" />
        <property name="port" value="587" />
        <property name="username" value="<!-- Source Email Address -->" />
        <property name="password" value="<!-- Source Email Password -->" />
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.debug">true</prop>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
                <prop key="mail.smtp.socketFactory.port">465</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
            </props>
        </property>
    </bean>
    
    <!-- Spring Email Attachment Configuration -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- Maximum Upload Size In Bytes -->
        <property name="maxUploadSize" value="20971520" />
        <!-- Maximum Size Of File In Memory (In Bytes) -->
        <property name="maxInMemorySize" value="1048576" />
    </bean>
   
    <!-- Resolves Views Selected For Rendering by @Controllers to *.jsp Resources in the /WEB-INF/ Folder -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <!-- Send Email Exception Resolver i.e. In Case Of Exception The Controller Will Navigate To 'error.jsp' & Will Display The Exception Message -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<prop key="java.lang.Exception">error</prop>
			</props>
		</property>
	</bean>	
</beans>

Notes:

This file is loaded by the Spring’s Dispatcher Servlet which receives all the requests coming into the application and dispatches them to the controller for processing. There are four beans declared in this configuration which draws our attention:

  • InternalResourceViewResolver: This bean declaration tells the framework how to find the physical JSP files according to the logical view names returned by the controllers, by attaching the prefix and the suffix to a view name. For e.g. If a controller’s method returns home as the logical view name, then the framework will find a physical file home.jsp under the /WEB-INF/views directory
  • <context:component-scan />: This tells the framework which packages to be scanned when using the annotation-based strategy. Here the framework will scan all classes under the package: com.jcg.spring.mvc.email
  • mailSender: This bean id configures the SMTP server settings and the JavaMail properties. This bean is injected into the spring controller class
  • multipartResolver: This bean id is for parsing the multipart request with the CommonsMultipartResolver implementation which is based on the Apache Commons File Upload. We will also configure the file upload settings as follows:
    • maxUploadSize: It is the maximum size (in bytes) of the multipart request, including the upload file. For this example, it is set to 20 MB
    • maxInMemorySize: It is a threshold (in bytes) beyond which the upload file will be saved to the disk instead of in the memory. For this example, it is set to 1 MB
  • SimpleMappingExceptionResolver: This specifies the error.jsp which handles the exceptions

3.3.2 Web Deployment Descriptor

The web.xml file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests and specifies the default page (i.e. emailForm.jsp) when accessing the application. Dispatcher servlet here acts as a front controller. Add the following code to it:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>Spring Mvc Email Example</display-name>
   
    <!-- Spring Configuration - Processes Application Requests -->
    <servlet>
        <servlet-name>SpringController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringController</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>   
    
    <!-- Welcome File List -->
    <welcome-file-list>
    	<welcome-file>emailForm.jsp</welcome-file>
  	</welcome-file-list>
</web-app>

3.4 Creating JSP Views

Spring MVC supports many types of views for different presentation technologies. These include – JSP, HTML, XML etc. So let us write a simple view in SpringMvcEmail/src/main/webapp/WEB-INF/views.

Right-click on SpringMvcEmail/src/main/webapp/WEB-INF/views folder, New -> JSP File.

Fig. 15: JSP Creation

Fig. 15: JSP Creation

Verify the parent folder location as: SpringMvcEmail/src/main/webapp/WEB-INF/views and enter the filename as: emailForm.jsp. Click Finish.

Fig. 16: emailForm.jsp

Fig. 16: emailForm.jsp

This is a simple form with three fields: Email To, Subject, and Message which are the necessary attributes for a simple outgoing email message. There are few notices for this HTML form i.e.

  • action="sendEmail": This specifies the action name which will handle submission of this form
  • enctype="multipart/form-data": This tells the browser that this form contains the multipart data so it will construct a multipart request to be sent to the SMTP server
  • <input type="file" … />: This tag shows a file browse button from which the user can pick up a file

Add the following code to it:

emailForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>Spring MVC Email Example</title>
	    <style type="text/css">
	    	#sendEmailBtn {
				float: left;
    			margin-top: 22px;
    		}
    	</style>
	</head>

	<body>
	    <center>
	        <h2>Spring MVC Email Example</h2>
	        <form id="sendEmailForm" method="post" action="sendEmail" enctype="multipart/form-data">
	            <table id="emailFormBeanTable" border="0" width="80%">
	                <tr>
	                    <td>Email To: </td>
	                    <td><input id="receiverMail" type="text" name="mailTo" size="65" /></td>
	                </tr>
	                <tr>
	                    <td>Subject: </td>
	                    <td><input id="mailSubject" type="text" name="subject" size="65" /></td>
	                </tr>
	                <tr>
	                    <td>Message: </td>
	                    <td><textarea id="mailMessage" cols="50" rows="10" name="message"></textarea></td>
	                </tr>
	                <tr>
	                    <td>Attachment: </td>
	                    <td><input id="mailAttachment" type="file" name="attachFileObj" size="60" /></td>
	                </tr>
	                <tr>
	                    <td colspan="2" align="center"><input id="sendEmailBtn" type="submit" value="Send Email" /></td>
	                </tr>
	            </table>
	        </form>
	    </center>
	</body>
</html>

Repeat the step (i.e. Fig. 15) and enter the filename as: success.jsp.

Fig. 17: success.jsp

Fig. 17: success.jsp

This page will simply show a success message after the email has been sent. Add the following code it:

success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>Spring MVC Email Example</title>
	    <style type="text/css">
	    	#emailFormDiv {
	    		text-align: center;
    			padding-top: 16px;
	    	}
	    	
    		#emailFormPage {
    			text-decoration: none;
    			text-align: center;
    			cursor: pointer;
    		}
    		
    		#successMessage {
    			text-align: center; 
    			color: green; 
    			font-size: 25px; 
    			padding-top: 17px;
    		}
    	</style>
	</head>
	
	<body>
	    <center>
	    	<h2>Spring MVC Email Example</h2>
	    </center>
	    <div id="successMessage">
	        <strong>${messageObj}</strong>
	    </div>
	    <div id="emailFormDiv">
	    	<a id="emailFormPage" href="emailForm">Go To Email Form Page</a>
	    </div>
	</body>
</html>

Again repeat the step (i.e. Fig. 15) and enter the filename as: error.jsp.

Fig. 18: error.jsp

Fig. 18: error.jsp

This page displays an error message in case of exceptions thrown, such as the upload file’s size exceeds the limit or SMTP settings are wrong. Add the following code it:

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>Spring MVC Email Example</title>
	    <style type="text/css">
    		#errorMessage {
    			text-align: center; 
    			font-size: 25px; 
    			padding-top: 17px;
    		}
    		
    		#errorMessage span {
    			color: red;
    		}
    	</style>
	</head>

	<body>
	    <center>
	        <h2>Spring MVC Email Example</h2>
	    </center>
	    <br /> <br />
	    <div id="errorMessage">
	        <strong>Sorry, The Email Was Not Sent Because Of The Following Error!</strong>
	        <span id="exceptionTrace">${exception.message}</span>
	    </div>
	</body>
</html>

4. Run the Application

As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 19: How to Deploy Application on Tomcat

Fig. 19: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8085/SpringMvcEmail/

Server name (localhost) and port (8085) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 20: Email Form Page

Fig. 20: Email Form Page

The email form is displayed, type in required information and hit the Send Email button. It may take a while for the email to be sent and a successful message appears on the result page in case everything goes well.

Fig. 21: Email Sent Successfully

Fig. 21: Email Sent Successfully

In case of an error (such as network failure or the SMTP server could not be reached etc.), the error page will be displayed.

Fig. 22: Error Page

Fig. 22: Error Page

Now checking the customer’s mailbox and we should see the new email message.

Fig. 23: Customer Mailbox

Fig. 23: Customer Mailbox

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to create a sample Spring MVC application that allows the user to send an email message by filling a web form. Developers can download the sample application as an Eclipse project in the Downloads section, and remember to update the SMTP settings to match your email account.

7. Download the Eclipse Project

This was an example of Sending an email with Spring MVC.

Download
You can download the full source code of this example here: SpringMvcEmail

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area from our partners over at ZipRecruiter

 

Want to take your Java skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns