forked from vimal-java-dev/vimaltech-contact-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmtpEmailService.java
More file actions
57 lines (46 loc) · 1.89 KB
/
SmtpEmailService.java
File metadata and controls
57 lines (46 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.vimaltech.contactapi.service.impl;
import com.vimaltech.contactapi.dto.EmailRequest;
import com.vimaltech.contactapi.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
@Slf4j
@ConditionalOnProperty(name = "spring.mail.host")
public class SmtpEmailService implements EmailService {
private final JavaMailSender mailSender;
private final String from;
public SmtpEmailService(
JavaMailSender mailSender,
@Value("${app.mail.from}") String from
) {
this.mailSender = mailSender;
this.from = from;
}
@Override
@Async("emailExecutor")
public void sendEmail(EmailRequest request) {
try {
log.info("START: Sending email | to={} | thread={}",
request.getTo(), Thread.currentThread().getName());
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); // 🔥 CRITICAL FIX
message.setTo(request.getTo());
message.setSubject(request.getSubject());
message.setText(request.getBody());
// ✅ OPTIONAL but IMPORTANT
if (request.getReplyTo() != null && !request.getReplyTo().isBlank()) {
message.setReplyTo(request.getReplyTo().trim());
}
mailSender.send(message);
log.info("SUCCESS: Email sent | to={}", request.getTo());
} catch (Exception e) {
// ❗ DO NOT THROW in async
log.error("ERROR: Email failed | to={}", request.getTo(), e);
}
}
}