English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spring Java Mail

The Spring framework provides many useful interfaces and classes for sending and receiving emails.

org.springframework.mail The package is the root package that provides mail support in the Spring framework.

Spring Java Mail API

The following interfaces and classes for Java mail support in the Spring framework are as follows:

MailSender interface: It is the root interface. It provides basic functionality for sending simple emails. JavaMailSender interface: It is a subinterface of MailSender. It supports MIME messages. It mainly works with MimeMessageHelper classes together to create JavaMail MimeMessage , as well as attachments, etc. The Spring framework recommends using MimeMessagePreparator mechanism to use this interface. JavaMailSenderImpl class: It provides the implementation of the JavaMailSender interface. It supports JavaMail MimeMessages and Spring SimpleMailMessages. SimpleMailMessage class: Used to create simple emails, including from, to, cc, subject, and text emails. MimeMessagePreparator interface: It is a callback interface used to prepare JavaMail MIME messages. MimeMessageHelper class: It is a helper class used to create MIME messages. It supports inline elements such as images, typical email attachments, and HTML text content.

Example of sending email through Gmail server in Spring

Using two Spring mail classes:

SimpleMailMessage Used to create messages. JavaMailSenderImpl Used to send messages.

You need to create the following files to send emails through the Spring framework.

MailMail.java applicationContext.xml Test.java You need to load the mail.jar and activation.jar files to run this example.

Download mail.jar and Activation.jar or visit the Oracle website to download the latest version.


1)MailMail.java

This is a simple class that defines the mailSender attribute. At runtime, a MailSender object will be provided to this attribute.

In the sendMail() method, we are creating an instance of SimpleMailMessage and storing the information (such as from, to, subject, and message) in this object.

Here, the send() method of the MailSender interface is used to send a simple email.

package com.w3codebox;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
 
public class MailMail{
  private MailSender mailSender;
 
  public void setMailSender(MailSender mailSender) {
    this.mailSender = mailSender;
  }
 
  public void sendMail(String from, String to, String subject, String msg) {
        //creating message
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(msg);
        //sending message
    mailSender.send(message); 
  }
}

2)applicationContext.xml

In this xml file, we have created a bean for the JavaMailSenderImpl class. We need to define the values of the following properties:

Host Username Password javaMailProperties

We will also use the mailSender attribute to create a bean for the MailMail class. Now, the instance of JavaMailSenderImpl class will be set in the mailSender attribute of the MailMail class.

<?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
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="host" value="smtp.gmail.com" />
  <property name="username" value="[email protected]" />
  <property name="password" value="yourgmailpassword" />
  <property name="javaMailProperties">
     </props>
              <prop key="mail.smtp.auth">true</prop>/prop>
              <prop key="mail.smtp.socketFactory.port">465</prop>
              <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
              <prop key="mail.smtp.port">465</prop>
        </props>
  </property>
</bean>
<bean id="mailMail" class="com.w3codebox.MailMail">
  <property name="mailSender" ref="mailSender"> />
</bean>
</beans>

3)Test.java

This class retrieves the mailMail bean from the applicationContext.xml file and calls the sendMail method of the MailMail class.

package com.w3codebox;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test { 
public static void main(String[] args) {
  
Resource r = new ClassPathResource("applicationContext.xml");
BeanFactory b = new XmlBeanFactory(r);
MailMail m = (MailMail)b.getBean("mailMail");
String sender="[email protected]";//write here sender gmail id
String receiver="[email protected]";//write here receiver id
m.sendMail(sender,receiver,"hi","welcome");
  
System.out.println("success");
}
}

How to run this example

Load the spring jar file for core and Java mail Load mail.jar and activation.jar Change the username and password properties in applicationContext.xml and specify your gmail ID and password. Change the sender gmail ID and Receivermail ID in the Test.java file. Compile and run the Test class


An example of sending email using the server provided by the host provider in Spring

If you have your own site, you can use the mail server. MailMail.java and Test class will be the same. You just need to change the sender email ID in the Test.java file. Some changes need to be made in applicationContext.xml.

In the applicationContext.xml file, we are using:

mail.unitedsquaad.com as the hostname. Change it. [email protected] as the username. Change it. xxxxx as the password. Change it.

<?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
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="host" value="mail.unitedsquaad.com"> />
  <property name="username" value="[email protected]"> />
  <property name="password" value="xxxxx"> />
 
  <property name="javaMailProperties">
     </props>
              <prop key="mail.smtp.auth">true</prop>/prop>
           </props>
  </property>
</bean>
<bean id="mailMail" class="MailMail">
  <property name="mailSender" ref="mailSender"> />
</bean>
 
</beans>

send emails to multiple recipients

You can use the SimpleMailMessage class to send emails to multiple recipients. The SimpleMailMessage class's setTo(String [] recipients)The method is used to send messages to multiple recipients. Let's take a look at the simple code.

      ....
  public void sendMail(String from, String[] to, String subject, String msg) {
        //creating message
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);//passing array of recipients
    message.setSubject(subject);
    message.setText(msg);
        //sending message
    mailSender.send(message); 
  }
     ...

Spring MimeMessagePreparator example

We can use the MimeMessagePreparator interface to send mime messages. It has a method prepare(MimeMessage message).

Let's take a look at the simple code for sending mime messages.

  import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
public class MailMail{
  private JavaMailSender mailSender;
 
  public void setMailSender(JavaMailSender mailSender) {
    this.mailSender = mailSender;
  }
 
  public void sendMail(final String from, final String to, final String subject, final String msg) {
      
    MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {
          
                public void prepare(MimeMessage mimeMessage) throws Exception {
                   mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
                   mimeMessage.setFrom(new InternetAddress(from));
                   mimeMessage.setSubject(subject);
                   mimeMessage.setText(msg);
                }
        };
        mailSender.send(messagePreparator);
  }
}

The applicationContext.xml and Test.java files are the same as those provided above.


Sending an attachment via Spring MimeMessageHelper example

We can send a mime message with an attachment using the help of MimeMessageHelper class in Spring. It is recommended to use MimeMessagePreparator.

Let's take a look at a simple code for sending a mime message with an attachment (image).

import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailMail{
  private JavaMailSender mailSender;
 
  public void setMailSender(JavaMailSender mailSender) {
    this.mailSender = mailSender;
  }
 
  public void sendMail(final String from, final String to, final String subject, final String msg) {
    try{
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(msg);
    // attach the file
    FileSystemResource file = new FileSystemResource(new File("c:",/rr.jpg"));
    helper.addAttachment("mybrothermage.jpg", file);//image will be sent by this name
    mailSender.send(message);
    catch(MessagingException e){e.printStackTrace();}
  }
}

The applicationContext.xml and Test.java files are the same as those provided above.