Sending Email With Spring MVC Example (original) (raw)
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.
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
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
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.
<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>
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. | MailSender | It is the root interface which provides the basic functionality for sending simple emails. |
2. | JavaMailSender | It 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. | JavaMailSenderImpl | It provides the implementation of JavaMailSender interface which supports JavaMail MimeMessage and Spring SimpleMailMessage. |
4. | SimpleMailMessage | It is used to create a simple email message including from, to, cc, subject and text messages. |
5. | MimeMessagePreparator | It is a callback interface for the preparation of JavaMail MimeMessage. |
6. | MimeMessageHelper | It 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!
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
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
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
Select the Maven Web App Archetype from the list of options and click Next.
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
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
4.0.0 SpringMvcEmail SpringMvcEmail 0.0.1-SNAPSHOT warWe 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
4.0.0 SpringMvcEmail SpringMvcEmail war 0.0.1-SNAPSHOT SpringMvcEmail Maven Webapp http://maven.apache.org javax.servlet servlet-api 3.0-alpha-1 javax.servlet.jsp jsp-api 2.1 org.springframework spring-core 3.1.2.RELEASE org.springframework spring-context 3.1.2.RELEASE org.springframework spring-beans 3.1.2.RELEASE org.springframework spring-webmvc 3.1.2.RELEASE org.springframework spring-context-support 3.1.2.RELEASE javax.mail javax.mail-api 1.5.5 javax.mail mail 1.4.7 commons-fileupload commons-fileupload 1.2.1 commons-io commons-io 2.5 ${project.artifactId}
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
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)
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
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)
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
A new pop window will open and select the wizard as an XML
file.
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
Once the XML
file is created, we will add the following code to it:
spring-servlet.xml
<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>
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 physicalJSP
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 returnshome
as the logical view name, then the framework will find a physical filehome.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 theSMTP
server settings and the JavaMail properties. This bean is injected into the spring controller classmultipartResolver
: This bean id is for parsing the multipart request with theCommonsMultipartResolver
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 MBmaxInMemorySize
: 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 theerror.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
Spring Mvc Email Example<!-- 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>
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
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
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 formenctype="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 theSMTP
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"%>
Spring MVC Email Example<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>
Repeat the step (i.e. Fig. 15) and enter the filename as: 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"%>
Spring MVC Email Example