How to implement email sending functionality in Spring Boot?
In SpringBoot, you can implement email functionality using Spring’s email sending module, spring-boot-starter-mail, and configure the relevant email sending information in the application.properties file.
Firstly, import the spring-boot-starter-mail dependency in the pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Then configure the relevant information for sending emails in the application.properties file, such as:
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your-email@example.com
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Next, write the service class for sending emails in Java code. The example code is as follows:
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
javaMailSender.send(message);
}
}
Finally, simply call the sendEmail method from EmailService wherever you need to send an email. For example:
@Autowired
private EmailService emailService;
emailService.sendEmail("recipient@example.com", "Test Email", "This is a test email from SpringBoot.");
This way, you can implement email sending functionality in Spring Boot.