Send mail using spring-boot-starter-mail
.
Spring Boot is written in 2.0.9.
Add a dependency for spring-boot-starter-mail
.
pom.xml
<!--abridgement-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--abridgement-->
Set the following under spring.mail
.
With this setting, you can only send emails to Gmail / GSuite users (see below).
application.yml
spring:
mail:
host: aspmx.l.google.com
port: 25
This time it's for testing purposes, so I'm sending emails using Google's restricted Gmail SMTP server. With this setting, you can only send email to Gmail or GSuite users. See the documentation for more information on the Gmail SMTP server.
-Send emails from printers, scanners and apps -G Suite Administrator Help
Details of mail related settings in Spring Boot can be found in the documentation # Email
.
You can send an email at startup by adding the following.
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
@Component
public class MailUtil {
private final MailSender mailSender;
public MailUtil(MailSender mailSender) {
this.mailSender = mailSender;
this.sendMail();
}
public void sendMail() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom("[email protected]"); //Sender email address
mailMessage.setTo(/*Destination email address*/);
mailMessage.setCc(/*Email address to put in cc*/);
mailMessage.setBcc(/*Email address to put in bcc*/);
mailMessage.setSubject("Test title");
mailMessage.setText("Test message to send from local");
try {
mailSender.send(mailMessage);
} catch (MailException e) {
// TODO:Error handling
}
}
}
You can receive emails as follows.
Recommended Posts