DEV Community

walerick
walerick

Posted on

How I ensured user authentication, by sending emails in Spring Boot

How to send email in Java Spring Boot

First of all, add the spring-starter-mail dependency.
This can also be added by modifying your project pom.xml file to include the following

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

After you've successfully added the dependency, create a class object and access the the JavaMailSender Interface in your code by following these few steps:

  • Use the @Autowired annotation, to inject he JavaMailSender interface into the EmailService class.

  • Create a DemoMailMessage object.

  • Add email properties by using specific methods (setTo, setSubject, setText).

  • Call the send() method to send the email message.

Your code should be similar to this:

package com.example;

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

public class MyClass {
    @Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    public void sendEmail(String to, String subject, String body) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);

        mailSender.send(message);
    }
}
}
Enter fullscreen mode Exit fullscreen mode

Finally, you need to configure the SMTP server settings in your application.properties file as shown below

spring.mail.host=smtp.example.com
spring.mail.port=25
spring.mail.username=setusername
spring.mail.password=setpassword
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Enter fullscreen mode Exit fullscreen mode

Then you're good to go.

Since you made it this far, There is an internship program, that I stumbled upon twitter where developers can learn more and network better. There is also an option to get Certificate if you subscribe to the premium package instead.

Top comments (0)