当前位置: 首页 > news >正文

SpringBoot实现发邮件功能+邮件内容带模版

发送简单邮件+模版邮件

1.pom引入依赖

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

2.配置yaml文件

  mail:
    host: smtp.qq.com
    port: 465  # 必须改用SSL专用端口
    username: 配置发件人的邮箱
    password: 发件人的秘钥不是登录密码
    properties:
      mail:
        smtp:
          auth: true
          ssl:
            enable: true  # 显式启用SSL
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory  # 指定SSL工厂
        starttls:
          enable: false  # 禁用STARTTLS(与SSL互斥)

3.代码

    @GetMapping("/sendSimpleMail")
    public Result sendMail() {
        String recipientStr ="收件人邮箱";
        SendMailParam sendMailParam = new SendMailParam();
        sendMailParam.setContent("你好,现在是 "+System.currentTimeMillis()+",邮件发送成功!");
        mailUtil.sendSimpleMessage(recipientStr, "测试邮件主题", sendMailParam, "");
        return Result.ok();
    }

    @GetMapping("/sendTemplateMail")
    public Result sendTemplateMail() {
        String recipientStr ="收件人邮箱";
        mailUtil.sendThemplateMessage(recipientStr,"测试邮件主题");
        return Result.ok();
    }
 
import com.hmdp.config.MailConfig;
import com.hmdp.entity.SendMailParam;
import com.hmdp.service.ISendMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.*;

/**
 * @author don
 * @version 1.0.0
 * @ClassName SendMailServiceImpl.java
 * @Description TODO
 * @createTime 2024年03月06日 17:38:00
 */
@Service
@Slf4j
public class SendMailServiceImpl implements ISendMailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private TemplateEngine templateEngine;


    @Value("${spring.mail.username}")
    private String from;


    @Override
    public void sendSimpleMessage(String to, String subject, SendMailParam sendMailParam, String fileList) {
        try {
            MimeMessage mailMessage=mailSender.createMimeMessage();
            MimeMessageHelper helper=new MimeMessageHelper(mailMessage,true);
            //设置寄件人
            helper.setFrom(from);
            //设置邮件标题
            helper.setSubject(subject);
            //设置邮件内容
            helper.setText(sendMailParam.getContent());
            //设置收件人
            helper.setTo(to);
            // 发送邮件
            mailSender.send(mailMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendThemplateMessage(String to, String subject) {
        try {
            MimeMessage mailMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true);
            //设置寄件人
            helper.setFrom(from);
            //设置邮件标题
            helper.setSubject(subject);
            //设置收件人
            helper.setTo(to);
            //设置模板
            //thymeleaf模版解析成String
            Context ctx = new Context();
            ctx.setVariable("mailSubject", "测试主题");
            ctx.setVariable("noticeTime", "2025-03-18");
            ctx.setVariable("noticeNumber", "ASDF456");
            ctx.setVariable("name", "张三");
            ctx.setVariable("billDate", "2025-03-18");
            ctx.setVariable("groupCode", "45");
            ctx.setVariable("creator", "admin");
            ctx.setVariable("content", "hello world !");
            //模板填充数据
            String htmlContent = templateEngine.process("data", ctx);
            helper.setText(htmlContent, true);
            // 发送邮件
            mailSender.send(mailMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

 
}

4.模板位置及内容 

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head> 
<meta charset="utf-8"> 
<title>表格</title> 
</head>
<body>

<table border="1">
<tr>
  <td><h4>邮件主题</h4></td>
  <td colspan="5">
    <a th:href="@{http://ip/}" th:text="${mailSubject}"> </a>
  </td>
</tr>
<tr>
  <td><h4>通知时间</h4></td>
  <td colspan="5" th:text="${noticeTime}"></td>
</tr>
<tr>
  <td><h4>通知类型</h4></td>
  <td colspan="3">
    <span th:text="${noticeText}" th:style="${noticeText == '正常通知' ? 'color: green;' : 'color: red;' }"></span>
  </td> 
  <td><h4>任务编号</h4></td>
  <td  colspan="3">
	  <span style="color: red;"><span th:text="${noticeNumber}"></span></span>
  </td> 
</tr>
<tr>
  <td><h4>姓名</h4></td>
  <td colspan="3" th:text="${name}">

  </td> 
  <td><h4>日期</h4></td>
  <td  colspan="3" th:text="${billDate}">

  </td> 
</tr>
<tr>代码</h4></td>
  <td colspan="3" th:text="${groupCode}">

  </td> 
  <td><h4>创建者</h4></td>
  <td  colspan="3" th:text="${creator}">

  </td> 
</tr>
<tr>
  <td><h4>通知内容</h4></td>
  <td colspan="5">

      <div>
          <span th:utext="${content}"></span>
      </div>
  </td>
</tr>
</table>

</body>
</html>
<style>
  table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
  }
  div {
    margin-top:10px;
  }
  .icon {
    text-align: center;
    display: inline-block;
    width: 20px;
    height: 20px;
    background-color: yellowgreen;
    border-radius: 50%;
    color: #fff;
    margin-right: 4px;
    font-weight: bold;
  }

  .icon.success {
    background-color: yellowgreen;
    line-height: 22px;
  }
  .icon.error {
    background-color: red;
    line-height: 18px;
  }
  td {
    padding: 0px 10px;
  }

</style>

5.效果示例

 6.模版邮件注意事项

     代码里的字段要和模板里的字段对应上

相关文章:

  • 理解大模型的function call ,思维链COT和MCP 协议
  • H-ZERO自定义全局字体 支持项目个性化字体需求
  • 【WRF-Urban】城市冠层/建筑楼层设置
  • C++ 学习笔记(三)—— 入门+类和对象
  • MySQL 8主从复制配置最佳实践
  • uniapp 实现微信小程序电影选座功能
  • leetcode-50.Pow(x,n)
  • 火山云对比阿里云的优势在哪里
  • 【Linux操作系统——学习笔记二】Linux简单导航命令操作
  • 安徽建筑安全员A证考试的报名条件是什么?
  • spring boot 过滤器简单demo
  • Java实现字符串大写字母转小写的多种方法及优化策略
  • Web Component 教程(三):生命周期方法的触发时机与实际应用
  • 【C++】树和二叉树的实现(下)
  • 数据库:一文掌握 MongoDB 的各种指令(MongoDB指令备忘)
  • uniapp常用组件
  • 在 Vue.js 中使用递归组件:轻松处理嵌套数据结构
  • Python 爬虫(2)Web请求
  • 第六章-PHP错误处理
  • Hexo博客部署免费Twikoo评论系统新手教程
  • 深圳两家会所涉卖淫嫖娼各被罚7万元逾期未缴,警方发催告书
  • 浙江一民企拍地后遭政府两次违约,“民告官”三年又提起民事诉讼
  • 洲际酒店:今年第一季度全球酒店平均客房收入同比增长3.3%
  • “80后”计算机专家唐金辉已任南京林业大学副校长
  • 城管给商户培训英语、政银企合作纾困,上海街镇这样优化营商环境
  • 人民日报钟声:中方维护自身发展利益的决心不会改变