代码之家  ›  专栏  ›  技术社区  ›  Michał

JavaMailSender中的句柄异常

  •  0
  • Michał  · 技术社区  · 7 年前

    我创建了简单的邮件服务来通过电子邮件发送内容。它可以工作,但我不知道如何处理异常(我的想法是在HTML视图中打印一些信息或在404页上重定向)

    邮件服务:

    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);
    
            }
        }
    
    }
    

    控制器中的用法:

            try {
            mailService.sendMail(templateEngine.process("summary/mailTemplate", ctx), userInfo.getEmail(), true, "Mail title", "attachment title);
            } catch (IOException e) {
                e.printStackTrace();
                return "redirect:/404";
            }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Michał    7 年前

    我创建了处理邮件异常逻辑的服务

    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";
            }