Let's see how we can send emails with the Springboot application.
Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Properties
Open the application.properties file and add the properties shown below. Set the host and port depending on the kind of hosts that you want to use. Then add the sender email address and password. For gmail we have to use an app password which provides a better security by limiting the access scopes and use it.
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<mail@gmail.com>
spring.mail.password=<app_access_password>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
How to create the gmail app password
Log in to the google account -> security -> 2-step verification
Choose the app passwords at the bottom
Enter a name and click 'save'
Coding
Sending Text
@Controller
public class EmailController {
@Autowired
private JavaMailSender mailSender;
@GetMapping("/email")
public void sendEmail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("<senderEmail@gmail.com>");
message.setTo("<receiverEmail>");
String subject = "Subject";
String content = "Content";
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
}
Done
References
Spring Boot Email Sending Tutorial and Code Examples (codejava.net)
Spring Boot Email Sending Tutorial and Code Examples
www.codejava.net
Sign in with app passwords - Google Account Help
앱 비밀번호로 로그인 - Google 계정 고객센터
도움말: 앱 비밀번호는 권장되지 않으며 대부분의 경우 필요하지 않습니다. 계정을 안전하게 보호하려면 'Google 계정으로 로그인'을 사용하여 앱을 Google 계정에 연결하세요. 앱 비밀번호란 보안
support.google.com
'Backend > Java' 카테고리의 다른 글
Polymorphism (0) | 2024.01.01 |
---|---|
Method Overriding VS Overloading (1) | 2023.12.31 |
java: error: release version 21 not supported (0) | 2023.12.30 |
Lombok (0) | 2023.12.29 |
Inheritance (0) | 2023.12.28 |