我创建了简单的MailService来通过电子邮件发送内容。它有效,但我不知道如何处理异常(我的想法是在HTML视图中打印一些信息或在404页面上重定向)
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("applica@applica.ai"); 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); } } }
Controller中的用法:
try { mailService.sendMail(templateEngine.process("summary/mailTemplate", ctx), userInfo.getEmail(), true, "Mail title", "attachment title); } catch (IOException e) { e.printStackTrace(); return "redirect:/404"; }
答案 0 :(得分:0)
我已经创建了处理邮件异常逻辑的服务
public class MailSendingException extends Exception { public MailSendingException() { } public MailSendingException(String s) { super(s); } }
和此特定视图的控制器
@Controller public class errorMailController { @GetMapping("/errorMail") public String errorMail() { return "errorMail"; } }
然后我在发送电子邮件的地方使用了它
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"; }