Skip to content

spring-guides/getting-started-guides

Repository files navigation

This guide demonstrates how to create a Spring Boot application that sends an email. It is unlikely that you want an application that does nothing more than send an email, but you can use this guide to put the ability to send email into other programs.

For this guide, we also show an extensible way to structure a Spring Boot application. This structure also makes it easier to add the ability to send email to your applications.

We also chose to show how to create a command-line application with Spring Boot. Most Spring guides show web applications, but command-line applications are sometimes helpful.

What You Will Build

You will build a Spring Boot application that sends an email message. This application runs from the command line.

Starting with Spring Initializr

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this guide.

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.

  3. Click Add Dependencies.

  4. Choose Java Mail Sender.

    Tip
    You can quickly find the Java Mail Sender package by typing mail.
  5. Click Generate.

  6. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

Note
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.
Note
You can also fork the project from Github and open it in your IDE or other editor.

About the structure

In this guide, we create two classes beyond what the Initializr created for us. The Initializr gave us a class with a main method to serve as the entry point for our application. We could put the remaining functionality in that class, but we do not recommend doing so. As soon as you need to modify or extend your program, you are likely to regret that structure. As a more maintainable and extendable structure, we create a configuration class and a POJO (Plain Old Java Object) to handle the implementation. This is a typical structure for our Spring Boob applications, and we find that it works well.

Create a Configuration class

To define the configuration for our program, we need to create a configuration class:

@Configuration
public class MailConfiguration {

    @Bean
    public Mailer mailer(JavaMailSender javaMailSender) {
        return new Mailer(javaMailSender);
    }

    @Bean
    public ApplicationRunner applicationRunner (Mailer mailer) {
        return new ApplicationRunner() {
            @Override
            public void run(ApplicationArguments args) throws Exception {
                mailer.sendEmail();
            }
        };
    }
}

The @Configuration annotation marks this class as a Spring Boot configuration class, which Spring Boot then discovers.

In our configuration class, we need two beans (each marked with the @Bean annotation). One bean defines the mailer, while the other makes the application into a command-line application.

Creating the Mailer Class

To create the functionality, we need to create a Mailer class:

public class Mailer {
    private JavaMailSender javaMailSender;

    public Mailer(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    void sendEmail() throws MessagingException, IOException {

        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setTo("[email protected]");
        msg.setFrom("[email protected]");

        msg.setSubject("Test from Spring Boot");
        msg.setText("Hello, World!");

        javaMailSender.send(msg);

    }
}

The Mailer class uses JavaMailSender to send an email with the specified details. We have used fixed data here, but you could get the details from a database record or other dynamic source in a real-world application.

As mentioned earlier, the Mailer class is a POJO. Using one or more configuration classes with POJOs for implementation lets you separate your program into manageable pieces that you can readily maintain and extend.

Defining Application Properties

Sending email requires some information that, as a useful pattern, we store in the application.properties file:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=username
spring.mail.password=password

# Other properties
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable=true

You need to replace the username and password with real values.

NOTE

If you use Gmail, as we did in this example, the password needs to be an app password. Google has a help page that explains how to make one.

NOTE

The timeout values are optional. However, without them, the application waits forever, which is probably not what you want.

Running the Application

The following command runs your application from Maven:

./mvnw spring-boot:run

The following command runs your application from Gradle:

./gradlew bootRun

You can then check the target email account for your "Hello, World!" message from your Spring Boot application.

Summary

Congratulations! You’ve just developed a command-line Spring Boot application that sends an email. You can use the structure (configuration class and worker class) to implement all kinds of functionality with Spring Boot. You can also use this simple email implementation to send email from your Spring Boot applications.

About

Getting Started Guide template :: The template for new guides and also the place to request them.

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors 7