Sending emails using JavaMail

Now, let's implement the sending email feature using JavaMail. We will also use FreeMarker as the template engine to create the body of the email message.

First of all, let's add the following dependencies to pom.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
...
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>

The spring-boot-starter-mail starter provides interfaces, such as JavaMailSender, to make the implementation of sending email relatively easy, as you will see in this section. With the presence of the FreeMaker library, Spring Boot will automatically create an instance of freemarker.template.Configuration. By default, the template loader path is classpath:/templates/, which has been used to store Thymeleaf view templates. It is better that we separate the view templates from the mail templates by putting them in different folders. Let's change the loader path of FreeMarker by adding the following property to application.properties:

spring.freemarker.template-loader-path=classpath:/mail-templates/

To send emails out, JavaMail needs to connect to a Simple Mail Transfer Protocol (SMTP) server. In our local development environment, we have several options. We can send emails through Gmail’s SMTP server or Amazon's SES Service. However, this requires the recipient's email address to be valid. In fact, in our local dev environment, we usually do not need to actually receive the email but only to verify that our application does send out the correct message. For that, what we actually need is an SMTP server that we can use to check the email message the application sends out. The DebuggingServer implementation of Python’s standard library, smtpdprovides exactly that. It will discard the messages received and print them out to the Terminal. After installing Python, you can start a debugging SMTP server using the following command:

python -m smtpd -n -c DebuggingServer localhost:1025

As you can see, in this command, the SMTP server's host is localhost and it listens to port 1025. We will use this SMTP server for our local dev environment in this book. Now, let's add the following configuration to application.properties so that JavaMail can connect to this SMTP server:

spring.mail.host=localhost
spring.mail.port=1025
spring.mail.properties.mail.smtp.auth=false
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.210.71