spring boot之邮件发送

pom包配置



    org.springframework.boot
    spring-boot-starter-mail



    org.springframework.boot
    spring-boot-starter-freemarker
   

模板引擎配置

spring:
  freemarker:
    template-loader-path: classpath:/templates/

邮件服务器的配置

spring:
    mail
        host: smtp.qq.com 
        username: [email protected] 
        password: cumhxmicujosbjii #开启POP3之后设置的客户端授权码 
        default-encoding: UTF-8

简单的文本邮件

@Override
public void sendSimpleMail(String to, String subject, String content) throws MailException {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from); // 邮件发送者
    message.setTo(to); // 邮件接受者
    message.setSubject(subject); // 主题
    message.setText(content); // 内容

    mailSender.send(message);
}

发送带图片的邮件

controller的代码

@ApiOperation(value = "html邮件测试" ,  notes="html邮件测试")
@GetMapping("/testHtml")
public ResultVo testHtml() throws IOException, TemplateException, MessagingException {
    Map model = new HashMap();
    model.put("UserName", "yao");
    Template template = configuration.getTemplate("welcome.ftl");
    String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

    emailService.sendHtmlMail("[email protected]","html邮件",html);
    return ResultUtils.success();
}

service的代码

@Override
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();
    //true 表⽰示需要创建⼀一个 multipart message
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    mailSender.send(message);
}

你可能感兴趣的:(spring boot之邮件发送)