The Spring Framework provides a straightforward abstraction for sending email by using the JavaMailSender interface, and Spring Boot provides auto-configuration for it as well as a starter module. Start by creating a new project which uses the “mail” starter module:
spring init -dmail demo-mail
The following dependencies will be added:
<?xml version="1.0" encoding="UTF-8"?><project>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Next, add a class that uses the JavaMailSender interface to send mail messages:
package com.example.demomail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
@Service public class MailClient {
private JavaMailSender mailSender;
@Autowired public MailClient(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void prepareAndSend(String recipient, String message) {
MimeMessagePreparator messagePreparator = mimeMessage -> {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);messageHelper.setFrom("john.doeATgmail.com");messageHelper.setTo(recipient);messageHelper.setSubject("Sample mail subject");messageHelper.setText(message);
};
try {
mailSender.send(messagePreparator);
} catch (MailException e) {
// runtime exception; compiler will not force you to handle it
}
}
}
Finally, you can include the SMTP configuration into the application.properties file:
spring.mail.host=localhost spring.mail.port=25 spring.mail.username= spring.mail.password= spring.mail.protocol=smtp
Mail properties can also be defined programmatically using the JavaMailSenderImpl. For example:
@Bean public JavaMailSender getJavaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("john.doeATgmail.com");
mailSender.setPassword("12345678");
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
Found the article helpful? if so please follow us on Socials