美文网首页
spring boot之邮件发送

spring boot之邮件发送

作者: 松松土_0b13 | 来源:发表于2019-07-15 16:26 被阅读0次

pom包配置

<!--邮件-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--freemarker模板引擎-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>   

模板引擎配置

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

邮件服务器的配置

spring:
    mail
        host: smtp.qq.com 
        username: xxx@qq.com 
        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<String, Object> model = new HashMap();
    model.put("UserName", "yao");
    Template template = configuration.getTemplate("welcome.ftl");
    String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

    emailService.sendHtmlMail("249982536@163.com","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之邮件发送

      本文链接:https://www.haomeiwen.com/subject/bhugkctx.html