spring boot集成发送邮件

版权声明:原创欢迎转载,转载请注明出处 https://blog.csdn.net/ye17186/article/details/88125787

本例中将发送邮件封装成了工具类,在业务代码中可以随时随地的调用,十分方便

一、pom中加入mail的依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

二、yml中配置mail服务相关的内容

spring:
  mail:
    host: smtp.163.com # 邮箱服务器地址
    username: [email protected] # 用户名
    password: your-password # 密码

三、发送邮件工具类EmailUtils封装

@Slf4j
public class EmailUtils {

    private static JavaMailSender mailSender = SpringUtils.getBean(JavaMailSender.class);

    /**
     * 执行发送邮件
     *
     * @param from 发件人
     * @param to 收件人
     * @param cc 抄送人
     * @param subject 主题
     * @param content 内容
     * @param isHtml 是否为HTML
     */
    public static void send(String from, String to, String cc, String subject, String content,
        boolean isHtml) {

        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(from);
            helper.setTo(to);
            if (StringUtils.isNoneEmpty(cc)) {
                helper.setCc(cc);
            }
            helper.setSubject(subject);
            helper.setText(content, isHtml);
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            log.info("发送邮件失败", e);
        }
    }
}

其中的SpringUtils如何封装,参见点这里

这样我们就可以愉快的中代码中EmailUtils.send()来发送邮件了。

补充:

1、发送带附件的邮件。

上文EmailUtils工具类中的MimeMessageHelper对象,有一个添加附件的方法,如下使用即可:

helper.addAttachment("fileName", file);

2、发送模板邮件

很多情况,我们发送邮件的格式是相对固定了,我们只需要替换其中的变量即可。这种场景,我们可以使用thymeleaf等来完成,其他模板引擎也可以,可以自行选择

①pom中添加依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

②在resorces/templates下创建模板文件myEmail.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <p th:text="'你好:' + ${username} + ',欢迎加入我们'"></p>
  <br/>
  <a href="#" th:href="@{ https://blog.csdn.net/ye17186 }">学习更多内容</a>
</body>
</html>

③、正确使用

/**
 * @author ye17186
 * @version 2019/3/4 17:40
 */
@RestController
public class EmailController {

    @Autowired
    TemplateEngine templateEngine;

    @PostMapping("test")
    public ApiResp<String> sendEmail() {
        Context context = new Context();
        context.setVariable("username", "yclouds");
        String html = templateEngine.process("MyEmail", context);
        EmailUtils.send("[email protected]", "[email protected]", "[email protected]", "欢迎加入YClouds", html, true);
        return ApiResp.retOK();
    }
}

④效果,可以看到模板html中的变量username,成功替换成了你想要的值。

GitHub地址:https://github.com/ye17186/spring-boot-learn

猜你喜欢

转载自blog.csdn.net/ye17186/article/details/88125787