Reputation: 87
I created simple MailService to send content by email. It works but I don't know how to handle exceptions (my idea is to print some info in HTML view or redirect on 404 page)
MailService:
public class MailService { public final JavaMailSender emailSender; public void sendMail(String content, String to, Boolean isHtml, String subject, String path) { log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", true, isHtml, to, subject, content); MimeMessage mimeMessage = emailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, CharEncoding.UTF_8); message.setTo(to); message.setFrom("[email protected]"); message.setSubject(subject); message.setText(content, isHtml); FileSystemResource file = new FileSystemResource(path); message.addAttachment(file.getFilename(), file); emailSender.send(mimeMessage); log.debug("Sent e-mail to User '{}'", to); } catch (Exception e) { log.warn("E-mail could not be sent to user '{}'", to, e); } } }
Usage in Controller:
try { mailService.sendMail(templateEngine.process("summary/mailTemplate", ctx), userInfo.getEmail(), true, "Mail title", "attachment title); } catch (IOException e) { e.printStackTrace(); return "redirect:/404"; }
Upvotes: 0
Views: 3682
Reputation: 87
I've created service to handle logic of mail exception
public class MailSendingException extends Exception { public MailSendingException() { } public MailSendingException(String s) { super(s); } }
and controller for this specific view
@Controller public class errorMailController { @GetMapping("/errorMail") public String errorMail() { return "errorMail"; } }
and then I used it in place where I'm sending email
try { mailService.sendMail(templateEngine.process("summary/mailTemplate", ctx), userInfo.getEmail(), true, "Mail title", "attachment title); } catch (IOException e) { e.printStackTrace(); return "redirect:/404"; } catch (MailSendingException mse) { return "redirect:/errorMail"; }
Upvotes: 0