Trong bài này mình sẽ hướng dẫn các bạn gửi email trong ứng dụng spring boot.
Đầu tiên các bạn vào https://start.spring.io để tạo project mới, giữ mọi thứ mặc định, đổi tên group, artifact và name theo ý bạn muốn.
Mục Add Dependencies, chọn Java Mail Sender rồi nhấn Generate. Mở tệp được generated bằng IDE, mở file application.properties và điền đoạn mã dưới đây vào:
spring.application.name=demo
spring.mail.host = smtp.gmail.com
spring.mail.port = 587
spring.mail.username =
spring.mail.password =
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable = true
username và password bạn có thể lấy ở App Password https://myaccount.google.com, nhớ phải enable 2-Step Verification thì AP mới available. Tham khảo video dưới:
Giờ tạo Service:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class EmailSenderService {
@Autowired
private JavaMailSender mailSender;
public void sendSimpleMail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
}
Test send mail:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
@SpringBootApplication
public class DemoApplication {
@Autowired
private EmailSenderService emailSenderService;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@EventListener(ApplicationReadyEvent.class)
public void applicationReady() {
emailSenderService.sendSimpleMail("thoschwabing141@icloud.com", "Alert test", "are you ok?");
}
}
Chúc các bạn thành công!
Very helpful. Thank you very much.