Skip to content

Instantly share code, notes, and snippets.

@horlathunbhosun
Created May 19, 2024 12:23
Show Gist options
  • Save horlathunbhosun/32e9cb914c396cab62d63bc476ddf595 to your computer and use it in GitHub Desktop.
Save horlathunbhosun/32e9cb914c396cab62d63bc476ddf595 to your computer and use it in GitHub Desktop.
EmailService Class
@Service
@RequiredArgsConstructor
public class EmailService {
private final JavaMailSender emailSender;
@Value("${application.mail.sent.from}")
private String fromUsr;
public void sendEmail(String to, String subject, String body) throws MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setTo(to);
helper.setFrom(fromUsr);
helper.setSubject(subject);
helper.setText(body, true);
emailSender.send(message);
}
@RabbitListener(queues = "email_queue")
public void processEmailMessage(EmailDetailDTO emailDetailDTO) throws MessagingException {
String to = emailDetailDTO.getTo();
String subject = emailDetailDTO.getSubject();
String body = generateEmailBody(emailDetailDTO);
sendEmail(to, subject, body);
}
public String generateEmailBody(EmailDetailDTO emailDetailDTO) {
String templateName = emailDetailDTO.getTemplateName();
String template = loadEmailTemplate(templateName);
String body = template;
if (emailDetailDTO.getDynamicValue() != null) {
for (Map.Entry<String, Object> entry : emailDetailDTO.getDynamicValue().entrySet()) {
body = body.replace("{{" + entry.getKey() + "}}", entry.getValue().toString());
}
}
return body;
}
public String loadEmailTemplate(String templateName) {
ClassPathResource resource = new ClassPathResource("templates/emails/" + templateName + ".html");
try {
return StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error loading email template " + templateName, e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment