1. เพิ่ม mail starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. ตั้งค่า SMTP ใน 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
เก็บคีย์ไว้ในตัวแปรสภาพแวดล้อม อย่าเก็บใน repository
3. ส่งอีเมลข้อความธรรมดา
@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. ส่ง 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);
ส่งทั้งเวอร์ชันข้อความธรรมดาและ HTML และส่ง HTML เป็นเอกสารเต็มที่มีแท็ก <html> และ <body> HTML ที่มีแค่บางส่วนเป็นสัญญาณสแปมที่พบบ่อย
5. ยืนยันโดเมน
ก่อนใช้งานจริง เพิ่มโดเมนใน Sendcorex แล้วเผยแพร่ระเบียน SPF, DKIM และ DMARC ที่แสดง ใช้ชื่อผู้ส่งเดียวกันที่ตรงกับแบรนด์ในทุกอีเมล เครื่องมือสร้าง SPF และเครื่องมือสร้าง DMARC ของเราสร้างระเบียนให้คุณ