Spring – Send email with JavaMailSender

Learn to send emails in Spring 5 provided JavaMailSender interface. Here is a step by step example for sending email via gmail smtp server.

We will use javax.mail maven dependency to send emails while configuring mail properties in JavaMailSenderImpl class which implements JavaMailSender interface.

Read More: Send Email using Gmail SMTP Server (javax.email)

1. Maven dependencies

Follow maven project creation example for creating a project. Now import spring dependencies along with javax.mail.

<properties>
	<spring.version>5.2.0.RELEASE</spring.version>
	<email.version>1.16.18</email.version>
</properties>

<!-- Spring Context Support -->
<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>${email.version}</version>
</dependency>

2. JavaMailSender and Email templates

2.1. Java Configuration

Given is Java configuration for JavaMailSender which has been configured to use Gmail SMTP settings and we have configured a sample email template preconfigured with sender/reciever emails and email text.

You can customized the configuration as per your need.

import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

@Configuration
public class EmailConfig 
{
	@Bean
	public JavaMailSender getJavaMailSender() 
	{
	    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
	    mailSender.setHost("smtp.gmail.com");
	    mailSender.setPort(25);
	     
	    mailSender.setUsername("admin@gmail.com");
	    mailSender.setPassword("password");
	     
	    Properties props = mailSender.getJavaMailProperties();
	    props.put("mail.transport.protocol", "smtp");
	    props.put("mail.smtp.auth", "true");
	    props.put("mail.smtp.starttls.enable", "true");
	    props.put("mail.debug", "true");
	     
	    return mailSender;
	}
	
	@Bean
	public SimpleMailMessage emailTemplate()
	{
		SimpleMailMessage message = new SimpleMailMessage();
		message.setTo("somebody@gmail.com");
		message.setFrom("admin@gmail.com");
	    message.setText("FATAL - Application crash. Save your job !!");
	    return message;
	}
}

2.2. XML Configuration

In Spring context file, we will create a generic mail sender service which is capable of sending HTTP messages using gmail’s smtp server.

Also, we are making a pre-configured message which can be instantiated on the fly and use for sending the message.

<beans>

    <context:component-scan base-package="com.howtodoinjava" />    
    
    <!-- SET default mail properties -->
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	  	<property name="host" value="smtp.gmail.com"/>
	  	<property name="port" value="25"/>
	  	<property name="username" value="admin@gmail.com"/>
	 	<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>
    
    <!-- We can have some pre-configured messagess also which are ready to send -->

    <bean id="preConfiguredMessage" class="org.springframework.mail.SimpleMailMessage">
		<property name="to" value="somebody@gmail.com"></property>
		<property name="from" value="admin@gmail.com"></property>
  		<property name="subject" value="FATAL - Application crash. Save your job !!"/>
    </bean>
</beans>

3. Sending emails

This class uses the beans configured in applicationContext.xml file and use them to send messages.

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

@Service("emailService")
public class EmailService 
{
    @Autowired
    private JavaMailSender mailSender;
     
    @Autowired
    private SimpleMailMessage preConfiguredMessage;
 
    /**
     * This method will send compose and send the message 
     * */
    public void sendMail(String to, String subject, String body) 
    {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
    }
 
    /**
     * This method will send a pre-configured message
     * */
    public void sendPreConfiguredMail(String message) 
    {
        SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage);
        mailMessage.setText(message);
        mailSender.send(mailMessage);
    }
}

4. Email with attachments and inline resources

4.1. Email attachments

To attach a file with email, use MimeMessageHelper to attach the file with a MimeMessage.

public void sendMailWithAttachment(String to, String subject, String body, String fileToAttach) 
{
    MimeMessagePreparator preparator = new MimeMessagePreparator() 
    {
        public void prepare(MimeMessage mimeMessage) throws Exception 
        {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));
            mimeMessage.setSubject(subject);
            mimeMessage.setText(body);
            
            FileSystemResource file = new FileSystemResource(new File(fileToAttach));
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.addAttachment("logo.jpg", file);
        }
    };
    
    try {
        mailSender.send(preparator);
    }
    catch (MailException ex) {
        // simply log it and go on...
        System.err.println(ex.getMessage());
    }
}

4.2. Inline resources

Sometimes, we may want to attach inline resources such as inline images in email body.

Inline resources are added to the MimeMessage by using the specified Content-ID. Be sure to first add the text and then the resources. If you are doing it the other way around, it does not work.

public void sendMailWithInlineResources(String to, String subject, String fileToAttach) 
{
    MimeMessagePreparator preparator = new MimeMessagePreparator() 
    {
        public void prepare(MimeMessage mimeMessage) throws Exception 
        {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));
            mimeMessage.setSubject(subject);
            
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            
            helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);
            
            FileSystemResource res = new FileSystemResource(new File(fileToAttach));
            helper.addInline("identifier1234", res);
        }
    };
    
    try {
        mailSender.send(preparator);
    }
    catch (MailException ex) {
        // simply log it and go on...
        System.err.println(ex.getMessage());
    }
}

5. Demo

Time to test the spring mail sending program code. I am sending two messages from test code. One is instantiated and composed in test class itself, and another one is pre-configured message from applicationContext.xml file.

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringEmailTest 
{
	public static void main(String[] args) 
    {
        //Create the application context
        ApplicationContext context = new FileSystemXmlApplicationContext
        			("classpath:com/howtodoinjava/core/email/applicationContext.xml");
         
        //Get the mailer instance
        EmailService mailer = (EmailService) context.getBean("emailService");
 
        //Send a composed mail
        mailer.sendMail("somebody@gmail.com", "Test Subject", "Testing body");
 
        //Send a pre-configured mail
        mailer.sendPreConfiguredMail("Exception occurred everywhere.. where are you ????");
    }
}

Above call will send the emails.

Happy Learning !!

Leave a Reply

40 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.