Sending Mail with Spring Boot
This example sends email through Gmail.
Creating an App Password
If you use two-step verification, create an app password first.
Obtaining Dependency JAR Files
Download Java Mail and the JavaBeans Activation Framework.
Adding Dependencies
build.gradle
dependencies {
compile 'org.springframework.boot:spring-boot-starter'
+ compile 'org.springframework.boot:spring-boot-starter-mail'
+ compile fileTree(dir: 'libs', include: '*.jar')
}
Folder structure
|-build.gradle
|-libs/
| |-activation.jar
| `-javax.mail.jar
`-src/
Writing the Code
application.properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<Gmail account>
spring.mail.password=<password>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
If you use two-step verification, set an app password. Otherwise, set the normal login password.
Main.java
package sample.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
try (ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args)) {
ctx.getBean(Main.class).sendMail();
}
}
@Autowired
private MailSender sender;
public void sendMail() {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom("test@mail.com");
msg.setTo("recipient email address");
msg.setSubject("Send mail from Spring Boot");
msg.setText("You can send mail from Spring Boot.");
this.sender.send(msg);
}
}
Checking the Result
Open the recipient mailbox and check the delivered message.