Bài viết giúp bạn tạo ra ứng dụng gửi tin nhắn email với spring email
Tìm nhiên liệu cho phần application.properties
Vào phần google accout của bạn và làm theo các bước sau:
- Login
- Select OtherName
- Type any name you want then click generator
- In application.properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<youremail>
spring.mail.password=<The password was created in the yellow line above>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Bắt đầu code nào
- Create model pakage then create Mail.java file
Mail.java
public class Mail {
private String yourEmail;
private String subject;
private String message;
public String getYourEmail() {
return yourEmail;
}
public void setYourEmail(String yourEmail) {
this.yourEmail = yourEmail;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
- Create service pakage then create MailService Interface file
MailService Interface file
public interface MailService {
String sendEmail(Mail mail);
}
- Create pakage Impl then create MailServiceImpl.java file in service pakage
MailServiceImpl.java
@Service
@RequiredArgsConstructor
public class MailServiceImpl implements MailService {
private final JavaMailSender javaMailSender;
@Override
public String sendEmail(Mail mail) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom(mail.getYourEmail());
msg.setTo("codertom100@gmail.com");
msg.setSubject(mail.getSubject());
msg.setText(mail.getMessage());
javaMailSender.send(msg);
return "Send Successful!";
}
}
- Create controller pakage then create MailController.java file
MailController.java
@RestController
@RequiredArgsConstructor
public class MailController {
private final MailService mailService;
@PostMapping("/send")
public String sendMail(@RequestBody Mail mail){
return mailService.sendEmail(mail);
}
}