Theodora Fragkouli

About Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis.

Spring E-Mail Support – GMail SMTP Server Example

This is an example of Spring E-mail support via the Gmail SMTP Server. The Spring Framework provides a utility library for sending emails. The org.springframework.mail package contains all classes that provide the basic email support of the Spring Framework. Here we use its basic interface for sending emails, that is the MailSender interface. We are also making use of the SimpleMailMessage class, the basic class to create a simple email message. We enrich our example, creating a message with a specified template. Finally, we send an e-mail with an attachment file, using the JavaMailSender interface and the MimeMessage class.

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using Spring version 3.2.3 and the JDK 7_u_21.

Let’s begin,

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New-Maven-Project

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is checked, hit “Next” to continue with default values.

Maven-Project-Name-Location

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. We will set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample" and the project name as "springexample". Hit “Finish” to exit the wizard and to create your project.

Configure-Maven-Project

The Maven project structure is shown below:

Maven-project-structure

    It consists of the following folders:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add Spring 3.2.3 dependency

  • Locate the “Properties” section at the “Overview” page of the POM editor and perform the following changes:
    Create a new property with name org.springframework.version and value 3.2.3.RELEASE.
  • Navigate to the “Dependencies” page of the POM editor and create the following dependencies (you should fill the “GroupId”, “Artifact Id” and “Version” fields of the “Dependency Details” section at that page):
    Group Id : org.springframework Artifact Id : spring-web Version : ${org.springframework.version}

Alternatively, you can add the Spring dependencies in Maven’s pom.xml file, by directly editing it at the “Pom.xml” page of the POM editor, as shown below:
 
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>com.javacodegeeks.snippets.enterprise</groupId>
	<artifactId>springexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>
</project>

As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.

3. Add the JavaMail API dependency

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications.

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>com.javacodegeeks.snippets.enterprise</groupId>
	<artifactId>springexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<!-- Java Mail API -->
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4.3</version>
		</dependency>

		<!-- Spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>

</project>

4. A simple email with MailSender class and SimpleMailMessage class

SimpleMailExample.java class is a @Service annotated Spring bean. It uses the MailSender interface to create and send an email message. MailSender is injected with the @Autowired annotation in the mailSender property of the bean. The MailSender interface defines a strategy for sending simple emails.

SimpleMailExample.java class has a method sendMail(String from, String to, String subject, String msg). In this method a new SimpleMailMessage object is created. The SimpleMailMessage class encapsulates properties of a simple mail such as from, to, cc, subject, text. It provides getter and setter methods for these properties, so that they can be configured before the message is sent. Here, its properties are configured, via its setter methods. Then, the send(SimpleMailMessage simpleMessage) API method of MailSender is invoked to send the email message.

SimpleMailExample.java

package com.javacodegeeks.snippets.enterprise;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

@Service("sendMailExample")
public class SendMailExample {
	
		@Autowired
		private MailSender mailSender;
		
		public void setMailSender(MailSender mailSender) {
			this.mailSender = mailSender;
		}
	 
		public void sendMail(String from, String to, String subject, String msg) {
	 
			SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
	 
			simpleMailMessage.setFrom(from);
			simpleMailMessage.setTo(to);
			simpleMailMessage.setSubject(subject);
			simpleMailMessage.setText(msg);
			mailSender.send(simpleMailMessage);	
		}
	
}

Since MailSender is injected in another bean, we must define it as a bean in applicationContext.xml. The class to implement it is the org.springframework.mail.javamail.JavaMailSenderImpl class. This class provides properties to configure so as to define all settings needed to connect to a Server and send an email. Here, since we are using the GMail SMTP Server, we set the host property to smtp.gmail.com and the port property to 587. We also set the username and the password for the account at the mail host.

JavaMailSenderImpl class also provides a javaMailProperties field. Here, we can set the JavaMail properties, so that a Session is configured. All properties regarding the server and the protocol that will be used, or the authentication of the connection can be set here. Since we are using the SMTP protocol, the mail.smtp properties are set here. The mail.smtp.auth property is set to true so that the user will be authenticated. The mail.smtp.starttls.enable property is set to true to enable the use of the STARTTLS command (if supported by the server) to switch the connection to a TLS-protected connection before issuing any login commands. The mail.smtp.ssl.trust property is set to the name of the smtp server, so that trust depends on the certificate the smtp server presents.

applicationContext.xml

<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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

  <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" />
    
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="host" value="smtp.gmail.com" />
	<property name="port" value="587" />
	<property name="username" value="sender@gmail.com" />
	<property name="password" value="password" /> 
	<property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.smtp.ssl.trust">smtp.gmail.com</prop>
            </props>
	</property>
</bean>

</beans>

5. A simple email message with a template

In this step, SimpleMailExample.java class is enriched with templateMailMessage property. Through this property, the templateMailMessage bean is injected in SimpleMailExample.java class, using the @Autowired annotation. It is a bean of SimpleMailMessage class defined in applicationContect.xml. In the bean definition the template message is configured.

SimpleMailExample.java class is also enriched with another method, sendMailWithTemplate(String dear, String content). Here, a new SimpleMailMessage object is created, using the copy constructor of the SimpleMailMessage class. The parameter passed in the copy constructor is the templateMailMessage property. Thus, a reference to the template message is passed to the new object.

SimpleMailExample.java

package com.javacodegeeks.snippets.enterprise;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

@Service("sendMailExample")
public class SendMailExample {
	
		@Autowired
		private MailSender mailSender;
	
		@Autowired
		private SimpleMailMessage templateMailMessage;
		
		public void setSimpleMailMessage(SimpleMailMessage templateMailMessage) {
			this.templateMailMessage = templateMailMessage;
		}
		
		public void setMailSender(MailSender mailSender) {
			this.mailSender = mailSender;
		}
	 
		public void sendMail(String from, String to, String subject, String msg) {
	 
			SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
	 
			simpleMailMessage.setFrom(from);
			simpleMailMessage.setTo(to);
			simpleMailMessage.setSubject(subject);
			simpleMailMessage.setText(msg);
			mailSender.send(simpleMailMessage);	
		}
		
		public void sendMailWithTemplate(String dear, String content) {			 
			   SimpleMailMessage message = new SimpleMailMessage(templateMailMessage);
		 	   message.setText(String.format( templateMailMessage.getText(), dear, content));
		 	   mailSender.send(message);
		}
	
}

In applicationContext.xml file the templateMailMessage bean is defined. Here, we can set all the properties provided by SimpleMailMessage class, to create the template message.

applicationContext.xml

<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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

  <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" />
    
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="host" value="smtp.gmail.com" />
	<property name="port" value="587" />
	<property name="username" value="sender@gmail.com" />
	<property name="password" value="password" /> 
	<property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.smtp.ssl.trust">smtp.gmail.com</prop>
            </props>
	</property>
</bean>
  
 <bean id="templateMailMessage"
	class="org.springframework.mail.SimpleMailMessage"> 
	<property name="from" value="sender@gmail.com" />
	<property name="to" value="receiver@gmail.com" />
	<property name="subject" value="Hello" />
	<property name="text">
	   <value>
		<![CDATA[
			Dear %s,
			Mail Content : %s
		]]>
	   </value>
        </property>
</bean>

</beans>

6. A simple mail with an attachment, using the JavaMailSenderImpl, the MimeMessage and the MimeMessageHelper classes

Now let’s create and send a message with an attachment file. SendMailExample.java class now holds another property, javaMailSender of JavaMailSenderImpl class. As we mentioned above, this class is an implementation of the MailSender interface. We are using it here because it supports JavaMail MimeMessages. A MimeMessage represents a MIME style email message.

A new method is added to SendMailExample.java class. It is sendMailWithAttachment(String dear, String content) method. In this method a new MimeMessage is created by the createMimeMessage() API method of JavaMailSenderImpl class. Then a new MimeMessageHelper is created using the MimeMessage. The MimeMessageHelper is a helper class for easy population of a MimeMessage. All properties of the initial template message are passed to this helper class. It also adds the file to the message, using its addAttachment(String attachmentFilename, InputStreamSource inputStreamSource) API method. Then the message is passed to the javaMailSender so as to be sent.

SendMailExample.java

package com.javacodegeeks.snippets.enterprise;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service("sendMailExample")
public class SendMailExample {
	
		@Autowired
		private MailSender mailSender;
		
		@Autowired
		private JavaMailSenderImpl javaMailSender;
		
		@Autowired
		private SimpleMailMessage templateMailMessage;
		
		public void setJavaMailSender(JavaMailSenderImpl javaMailSender) {
			this.javaMailSender = javaMailSender;
		}

		public void setSimpleMailMessage(SimpleMailMessage templateMailMessage) {
			this.templateMailMessage = templateMailMessage;
		}
		
		public void setMailSender(MailSender mailSender) {
			this.mailSender = mailSender;
		}
	 
		public void sendMail(String from, String to, String subject, String msg) {
	 
			SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
	 
			simpleMailMessage.setFrom(from);
			simpleMailMessage.setTo(to);
			simpleMailMessage.setSubject(subject);
			simpleMailMessage.setText(msg);
			mailSender.send(simpleMailMessage);	
		}
		
		public void sendMailWithTemplate(String dear, String content) {			 
			   SimpleMailMessage message = new SimpleMailMessage(templateMailMessage);
		 	   message.setText(String.format( templateMailMessage.getText(), dear, content));
		 	   mailSender.send(message);
		}
		
		public void sendMailWithAttachment(String dear, String content) {
			 
			   MimeMessage message = javaMailSender.createMimeMessage();
		 
			   try{
				MimeMessageHelper helper = new MimeMessageHelper(message, true);
		 
				helper.setFrom(templateMailMessage.getFrom());
				helper.setTo(templateMailMessage.getTo());
				helper.setSubject(templateMailMessage.getSubject());
				helper.setText(String.format(
						templateMailMessage.getText(), dear, content));
		 
				FileSystemResource file = new FileSystemResource("C:\\hello\\java.txt");
				helper.addAttachment(file.getFilename(), file);
		 
			     }catch (MessagingException e) {
				throw new MailParseException(e);
			     }
			   javaMailSender.send(message);
		         }
	
}

7. Run the Application

All the above steps are checked in App.java class. We use the SendMailExample.java class to send a simple message, a message with a template and a message with an attachment. As a result, the receiver receives all three messages.
App.java

package com.javacodegeeks.snippets.enterprise;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

	public static void main(String[] args) {
		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		SendMailExample mm = (SendMailExample) context.getBean("sendMailExample");
        mm.sendMail("sender@gmail.com",
    		   "receiver@gmail.com",
    		   "Javacodegeeks email test", 
    		   "Testing.. \n Hello Spring Email Sender");
        mm.sendMailWithTemplate("dear", "content");
       mm.sendMailWithAttachment("dear", "content");
		context.close();
	}
}

 
This was an example of Spring E-Mail Support using the GMail SMTP Server.
Download the Eclipse project of this tutorial : SpringEmailExample.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books