Send an email using Java and Spring boot and gmail

problem

You wish to use email functionality in your web application that is built using the Spring framework. In this post we will see how to accomplish it using a Gmail account. Also, I will be using IntelliJ IDEA Ultimate edition (that supports Spring Framework)

SOLUTION

Let’s put into the mix Java Spring Boot Framework and JavaMailSender for sending emails.

STEP 1 - Create App password in your Google Account

In order to be able to tell our Java web app to use Gmail account, we need to create an application password from the Google Account. This password will be used for logging in instead of the personal one (for security reasons).

Let’s follow the steps below:

1. Log in to Google Account and from the menu choose Security tab as shown below:
2. Scroll to section Signing in to Google
3. Click on the App passwords
4. Choose Mail and Other and set a custom name e.g. "Java Spring email app"
5. Click Generate
6. Copy the password that appears in the yellow box
google-app-password
7. App password created and ready to use!
Current Google App passwords
STEP 2 - create spring project

Let’s create a new Java project using the Spring initializr

Java send email project Spring intellij
Choose dependency: Spring Web
Spring web dependency
Choose dependency: Java Mail Sender and click Next
javasend mail dependency
Fill project settings, Java 8, Maven and click Next
spring project settings
Enter project name, project location and hit Finish!
choose directory
sTEP 3 - coding
Set application properties

Open application.properties file and enter the following properties with your respective values:

application.properties
				
					spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your_gmail_account@gmail.com # REPLACE with your actual email
spring.mail.password=igkaukckgrkfqsti # REPLACE, use the password we generated earlier (yellow box)
spring.mail.properties.mail.smtp.auth=true 
spring.mail.properties.mail.smtp.starttls.enable=true

				
			
Create main class
SendEmailApplication.java
				
					package com.programmerabroad;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SendEmailApplication {

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

				
			

Let’s make the app runnable as any normal Java program by adding the classic @SpringBootApplication annotation and the main method.

Create a Controller
Sender.java
				
					package com.programmerabroad;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Sender {

    @Autowired
    private JavaMailSender javaMailSender;
}

				
			

This is a RestController and will be used with an endpoint to send email. In the code above we use the JavaMailSender dependency as a field that will be injected by the framework.

Let's add the endpoint

Let’s create a GET mapping to trigger the email sending. Add the following method to the class:

Sender.java
				
					 @GetMapping("/send")
    public String send(){

        //create an instance of SimpleMailMessage
        SimpleMailMessage message = new SimpleMailMessage();

        //set email's details
        message.setFrom("email_from"); //REPLACE with an email that will appear in the From section
        message.setTo("email_account_to_send"); //REPLACE with the email account to be sent to
        message.setSubject("test subject"); //REPLACE with email's subject
        message.setText("this is a test message"); //REPLACE with your email message/ body (text)

        //add error-handling
        try {
            //attempt to send email
            javaMailSender.send(message);
            return "email sent"; //all good, return a text message
        }catch (Exception e){ //Error occurred, return error message
            return "Sending email failed: " + e.getMessage();
        }
    }
				
			
Complete code for Sender class
Sender.java
				
					package com.programmerabroad;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Sender {

    @Autowired
    private JavaMailSender javaMailSender;

    @GetMapping("/send")
    public String send(){

        //create an instance of SimpleMailMessage
        SimpleMailMessage message = new SimpleMailMessage();

        //set email's details
        message.setFrom("email_from"); //REPLACE with an email that will appear in the From section
        message.setTo("email_account_to_send"); //REPLACE with the email account to be sent to
        message.setSubject("test subject"); //REPLACE with email's subject
        message.setText("this is a test message"); //REPLACE with your email message/ body (text)

        //add error-handling
        try {
            //attempt to send email
            javaMailSender.send(message);
            return "email sent"; //all good, return a text message
        }catch (Exception e){ //Error occurred, return error message
            return "Sending email failed: " + e.getMessage();
        }
    }
}

				
			
RUNNING

Let’s check if it works by running the main class.

If using IntelliJ, you can click on the run (play) button as shown below:

run SendemailApplication in IntelliJ IDEA

Or by executing the following Maven command:

				
					mvn spring-boot:run
				
			

You should be getting the Spring Boot – Tomcat output with the default port number 8080 as shown below:

output

Open a web browser, e.g. Firefox and go to http://localhost:8080/send

If all successful, the following message should be shown in the Web Browser:

Check your email client:

new email received

The email I got looks like this:

conclusion

In this post we saw a simple way to send an email using Java 8 and the Spring Framework in combination with a Google mail account.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x