Friday, February 22, 2019

Sending Email Using Spring Framework Example

In this post we’ll see the Spring framework support for sending emails.

Technologies Used

Examples showed in this post are written using the following-

  • Spring 5.0.8.Release
  • Java 10
  • Java Mail API

In this tutorial Maven is used to create a general Java project structure.


Maven Dependencies

You need to add following dependencies for sending mail using Spring framework.

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>5.0.8.RELEASE</spring.version>
</properties>
<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> 
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
</dependency>  
<dependency>
         <groupId>com.sun.mail</groupId>
         <artifactId>javax.mail</artifactId>
         <version>1.6.1</version>
</dependency>
<dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.6.1</version>
</dependency>
<dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
</dependency>

Spring framework Mail API

The Spring Framework provides a helpful utility library for sending email that abstracts the specifics of the underlying mailing system and is responsible for low level resource handling on behalf of the client.

org.springframework.mail package is the root level package for the Spring Framework’s email support.

  • MailSender interface- This interface defines a strategy for sending simple mails. Can be implemented for a variety of mailing systems due to the simple requirements.
  • SimpleMailMessage class- Models a simple mail message, including data such as the from, to, cc, subject, and text fields.
  • JavaMailSender interface- Adds specialized JavaMail features such as MIME message support to the MailSender interface by extending that interface.
  • JavaMailSenderImpl class- Implementation of the JavaMailSender interface, supporting both JavaMail MimeMessages and Spring SimpleMailMessages.
  • MimeMessagePreparator interface- Callback interface for the preparation of JavaMail MIME messages.
  • MimeMessageHelper class- Helper class for populating a MimeMessage. Typically used in MimeMessagePreparator implementations or JavaMailSender client code.

This package also contains a hierarchy of checked exceptions which provide a higher level of abstraction over the lower level mail system exceptions with the root exception being MailException.

Spring sending email example using JavaSenderImpl

First we’ll see a simple example of sending email using JavaSenderImpl class in the Spring framework using the Gmail SMTP.

For sending mail through Gmail’s SMTP server you need to tweek your Gmail account a little. After logging to your gmail account go to your account settings (https://myaccount.google.com/) - Sign-in & security- Apps with account access. There toggle the setting - Allow less secure apps to ON.

Spring email example – Configuration for JavaSender

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    
     <context:component-scan base-package="org.netjs.programs" />
     
     <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="GMAIL_USER_NAME"/>
        <property name="password" value="PASSWORD"/>
        <property name="javaMailProperties">
           <props>
                     <prop key="mail.transport.protocol">smtp</prop>
                     <prop key="mail.smtp.auth">true</prop>
                     <prop key="mail.smtp.starttls.enable">true</prop>
                     <prop key="mail.debug">true</prop>
              </props>
        </property>
     </bean>
     <bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
        <property name="from" value="FROM@gmail.com"/>
        <property name="to" value="TO@gmail.com"/>
        <property name="subject" value="Test Message"/>
    </bean>
</beans>

Using the JavaMailSenderImpl class you can configure the properties like host, port and other Java mail properties. Using the SimpleMailMessage you can configure the properties like from, to, subject. Please change the mail server settings and email settings.

Spring email example – Service class

@Service
public class EmailService {
 @Autowired
 private SimpleMailMessage templateMessage;
 @Autowired
 private MailSender mailSender;

 public void sendMail() {
  SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
  //msg.setTo(to);
  //Setting mail text
  msg.setText("This is a test mail sent through Spring framework");
  try{
   this.mailSender.send(msg);
  }
  catch (MailException ex) {
   // just printing
   System.out.println(ex.getMessage());
  }
 }
}

You can use the following class to test sending email.

public class App {
    public static void main( String[] args ){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
        EmailService emailService = (EmailService) context.getBean("emailService");
        emailService.sendMail();
        context.close();
    }
}

Log output (Abridged)

From: infojtutor@gmail.com
To: infojtutor@gmail.com
Message-ID: <594858858.0.1539095777456@user>
Subject: Test Message
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

This is a test mail sent through Spring framework
.
250 2.0.0 OK 1539095782 m27-v6sm31400671pff.187 - gsmtp
DEBUG SMTP: message successfully delivered to mail server
QUIT
221 2.0.0 closing connection m27-v6sm31400671pff.187 - gsmtp
Oct 09, 2018 8:06:19 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@6e1ec318: 
startup date [Tue Oct 09 20:06:11 IST 2018]; root of context hierarchy

Spring email example – Using MimeMessagePreparator

Here is another example of sending email using MimeMessagePreparator in Spring framework. In this example email settings are passed by using a properties file.

Spring email example – Configuration for JavaSender

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    
     <context:component-scan base-package="org.netjs.programs" />
     
     <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="GMAIL_USER_NAME"/>
        <property name="password" value="PASSWORD"/>
        <property name="javaMailProperties">
           <props>
                     <prop key="mail.transport.protocol">smtp</prop>
                     <prop key="mail.smtp.auth">true</prop>
                     <prop key="mail.smtp.starttls.enable">true</prop>
                     <prop key="mail.debug">true</prop>
              </props>
        </property>
     </bean>
</beans>

Spring email example – Service class

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
@Service
@Configuration
@PropertySource("classpath:email.properties")
public class EmailService {
 @Autowired
 private Environment env;
 @Autowired
 private JavaMailSender mailSender;


 public void sendMail() {
  MimeMessagePreparator preparator = new MimeMessagePreparator() {
   public void prepare(MimeMessage mimeMessage) throws Exception {
    mimeMessage.setRecipient(Message.RecipientType.TO,
    // Getting values from properties file
    new InternetAddress(env.getProperty("email.To")));
    mimeMessage.setFrom(env.getProperty("email.From"));
    mimeMessage.setSubject(env.getProperty("email.Subject"));
    mimeMessage.setText("This is the Spring email example.");
   }
  };
  try{
   this.mailSender.send(preparator);
  }
  catch (MailException ex) {
   // just printing
   System.out.println(ex.getMessage());
  }
 }
}

Note that in this case the mailSender property is of type JavaMailSender so that we are able to use the JavaMail MimeMessage class.

email.properties file

email.To=TO@gmail.com
email.From=FROM@gmail.com
email.Subject=Test Mail

Spring email with attachment example – Using MimeMessageHelper class

Here is an example of sending attachments with email using MimeMessageHelper class in Spring framework. In the example it shows how you can send attachment as well as inline resources.

Configuration for mail sender and email.properties file remain same as shown in the previous example.

Spring email with attachment example – Service class

@Service
@Configuration
@PropertySource("classpath:email.properties")
public class EmailService {
 @Autowired
 private Environment env;
 @Autowired
 private JavaMailSender mailSender;


 public void sendMail() {
  try{
   MimeMessage message = mailSender.createMimeMessage();
   // use the true flag to indicate you need a multipart message
   MimeMessageHelper helper = new MimeMessageHelper(message, true);
   // Getting values from properties file
   helper.setFrom(env.getProperty("email.From"));
   helper.setTo(env.getProperty("email.To"));
   helper.setSubject(env.getProperty("email.Subject"));
   helper.setText("Check out this image!");
   // inlining 
   helper.addInline("Inline image", new ClassPathResource("netjs.png"));
   // Attachment from class path
   helper.addAttachment("MyImage.png", new ClassPathResource("netjs.png"));
   //
   helper.addAttachment("MyPdf.pdf", new FileSystemResource("F:\\doc\\index.pdf"));
  
   this.mailSender.send(message);
  }
  catch (MessagingException ex) {
   // just printing
   System.out.println(ex.getMessage());
  }
 }
}

That's all for this topic Sending Email Using Spring Framework Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Example Program Using Automatic Configuration
  2. Spring Transaction Management JDBC Example Using @Transactional Annotation
  3. Spring MVC File Upload (Multipart Request) Example
  4. Insert\Update Using JDBCTemplate in Spring Framework
  5. Spring Batch Processing With List of Objects in batchUpdate() Method

You may also like-

  1. Injecting Inner Bean in Spring
  2. Spring MVC Checkbox And Checkboxes Form Tag Example
  3. How to Inject Prototype Scoped Bean in Singleton Bean
  4. Wiring Collections in Spring
  5. Difference Between ArrayList And LinkedList in Java
  6. Lambda Expression Examples in Java 8
  7. Compressing And Decompressing File in GZIP Format - Java Program
  8. Java Multithreading Interview Questions And Answers