Send email via Spring – JavaMailSender and MimeMessagePreparator

This tutorial will show you how to send a email via Spring framework’s email support. The Spring Framework provides a helpful utility library for sending email that shields the user from the specifics of the underlying mailing system and is responsible for low level resource handling on behalf of the client.

The org.springframework.mail.javamail.JavaMailSender interface adds specialized JavaMail features such as MIME message support to the MailSender interface (from which it inherits).

JavaMailSender also provides a callback interface for preparation of JavaMail MIME messages, called org.springframework.mail.javamail.MimeMessagePreparator.

Prerequisites

Eclipse 2019-12, Java at least 1.8, Gradle 6.4.1, Maven 3.6.3, Spring Boot Mail Starter 2.3.1, Java mail API 1.6.2

Project Setup

Create either gradle or maven based project in Eclipse. The name of the project is spring-email-javamailsender-and-mimemessagepreparator.

If you are creating gradle based project then you can use below build.gradle script:

buildscript {
	ext {
		springBootVersion = '2.3.1.RELEASE'
	}
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

plugins {
    id 'java-library'
    id 'org.springframework.boot' version "${springBootVersion}"
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    mavenCentral()
}

dependencies {
	implementation("org.springframework.boot:spring-boot-starter-mail:${springBootVersion}")
	implementation('javax.mail:javax.mail-api:1.6.2')
}

If you are creating maven based project then you can use below pom.xml file:

<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.roytuts</groupId>
	<artifactId>spring-email-javamailsender-and-mimemessagepreparator</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.1.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
		
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>javax.mail-api</artifactId>
			<version>1.6.2</version>
		</dependency>
	</dependencies>

    <build>
        <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>at least 8</source>
					<target>at least 8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Email Configuration

We will create an email configuration class where we will configure SMTP (Simple Mail Transfer Protocol) server details, from email address.

package com.roytuts.spring.email.javamailsender.and.mimemessagepreparator;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

@Configuration
public class EmailConfig {

	@Bean
	public JavaMailSender mailSender() {
		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

		mailSender.setHost("smtp.gmail.com");
		mailSender.setPort(587);
		mailSender.setUsername("gmail@gmail.com");
		mailSender.setPassword("gmail password");

		Properties javaMailProperties = new Properties();
		javaMailProperties.put("mail.smtp.auth", true);
		javaMailProperties.put("mail.smtp.starttls.enable", true);

		mailSender.setJavaMailProperties(javaMailProperties);

		return mailSender;
	}

}

We need to issue STARTTLS command otherwise you will get the error message similar to the following:

#smtplib.SMTPSenderRefused: (530, b'5.7.0 Must issue a STARTTLS command first. p7sm24605501pfn.14 - gsmtp', 'gmailaddress@gmail.com')

You will get below error if your security level is high:

#smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials x10sm26098036pfn.36 - gsmtp')

Therefore you need to lower your Gmail’s security settings.

Email Sender

Email sender class just does the right job for sending the email to the intended recipient.

package com.roytuts.spring.email.javamailsender.and.mimemessagepreparator;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;

@Component
public class EmailSender {

	@Autowired
	private JavaMailSender mailSender;

	public void sendEmail(final String subject, final String message, final String fromEmailAddress,
			final String toEmailAddresses) {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmailAddresses));
				mimeMessage.setFrom(new InternetAddress(fromEmailAddress));
				mimeMessage.setSubject(subject);
				mimeMessage.setText(message);
			}
		};
		try {
			mailSender.send(preparator);

			System.out.println("Email sending complete.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Main Class

A class is having main method with @SpringBootApplication annotation is enough to start up the Spring Boot application.

In this class we specify the subject, message and the recipient to send the email.

package com.roytuts.spring.email.javamailsender.and.mimemessagepreparator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MimeMessagePreparatorApp implements CommandLineRunner {

	@Autowired
	private EmailSender emailSender;

	public static void main(String[] args) {
		SpringApplication.run(MimeMessagePreparatorApp.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		emailSender.sendEmail("MimeMessagePreparator", "Email Message using MimeMessagePreparator",
				"gmail@gmail.com", "gmail@gmail.com");
	}

}

Testing the Application

Now execute the above main class, you will see your email will be sent to the intended recipient.

Console Output

Email sending complete.

Now check the mailbox, you will get a an email message. If you do not find the message in inbox then check the Spam folder.

I am sending email to myself so you are seeing me as a from email address.

Email in inbox:

javamailsender mimemessagepreparator email spring

Email details:

javamailsender mimemessagepreparator email spring

Source Code

Download

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *