1. Thêm mail starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. Cấu hình SMTP trong application.properties
spring.mail.host=smtp.sendcorex.com
spring.mail.port=587
spring.mail.username=${SENDCOREX_API_KEY}
spring.mail.password=${SENDCOREX_API_KEY}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Giữ key trong biến môi trường, không bao giờ trong repository.
3. Gửi email văn bản thuần
@Service
public class MailService {
private final JavaMailSender mailer;
public MailService(JavaMailSender mailer) { this.mailer = mailer; }
public void sendWelcome(String to) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom("Acme <hello@yourdomain.com>");
msg.setTo(to);
msg.setSubject("Welcome to Acme");
msg.setText("Thanks for signing up!");
mailer.send(msg);
}
}
4. Gửi HTML
MimeMessage mime = mailer.createMimeMessage();
MimeMessageHelper h = new MimeMessageHelper(mime, true, "UTF-8");
h.setFrom("hello@yourdomain.com", "Acme");
h.setTo(to);
h.setSubject("Your receipt");
h.setText("Your receipt is attached.", "<html><body><p>Your receipt is attached.</p></body></html>");
mailer.send(mime);
Truyền cả bản văn bản thuần và bản HTML, và gửi tài liệu HTML đầy đủ có thẻ <html> và <body> — HTML chỉ có phần rời rạc là tín hiệu spam phổ biến.
5. Xác thực tên miền
Trước khi chạy thật, thêm tên miền vào Sendcorex và công bố các bản ghi SPF, DKIM và DMARC hiển thị. Dùng cùng một tên người gửi khớp thương hiệu ở mọi email. Trình tạo SPF và trình tạo DMARC của chúng tôi tạo bản ghi giúp bạn.