首页 > 其他分享 >邮件发送与使用thymeleaf引擎重置密码邮件

邮件发送与使用thymeleaf引擎重置密码邮件

时间:2024-07-16 09:56:29浏览次数:11  
标签:String 重置 new thymeleaf html mail msg import 邮件

邮件发送

原生java-mail进行邮件发送; 前提:先登录邮箱,开启POP3/SMTP服务,使第三方可以使用授权码登录邮箱。

  @Test
    public void sendEmail(){
        String account="[email protected]";
        String pwd="KXNZHOZDMLTVWHOZ";
        //设置SMTP请求头
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.163.com");// QQ smtp.qq.com
        properties.put("mail.smtp.port", 465);// 默认端口号 25
        properties.put("mail.smtp.auth", "true");//服务端认证。
        properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息

        String to="[email protected]";
        //会话对象
        Session s = Session.getDefaultInstance(properties);
        try {
            Message msg = new MimeMessage(s);
            msg.setFrom(new InternetAddress(account));
            msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
            msg.addRecipient(Message.RecipientType.CC,new InternetAddress(account));
            msg.setSubject("今日新闻");
            msg.setText("飓风来袭");

            //邮差对象
            Transport transport = s.getTransport();
            transport.connect(account,pwd);
            transport.sendMessage(msg,msg.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

spring封装的spring-mail组件; 项目开发中我们选择sprng中封装的mail组件,使用简单方便。

  1. 添加mail启动器

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
  2. yml中配置登录邮箱,授权码,端口,ssl等。

    spring:  
      mail:
        protocol: smtp
        host: smtp.163.com
        port: 465
        username: [email protected]
        password: SYRZLRNOCSLFQJKA
        properties:
          mail:
            smtp:
              auth: true
              ssl:
                enable: true
  3. 测试邮件发送

    import org.junit.jupiter.api.Test;
    import org.springframework.boot.autoconfigure.mail.MailProperties;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    
    import javax.annotation.Resource;
    import javax.mail.internet.MimeMessage;
    import java.io.File;
    
    @SpringBootTest
    public class TestEmail {
        @Resource
        private JavaMailSender mailSender;
        @Resource
        private MailProperties mailProperties;
    
        //发送简单文本邮箱
        @Test
        public void springJavaSendMail() throws Exception {
            String to="[email protected]";
            MimeMessage msg = mailSender.createMimeMessage();
            MimeMessageHelper h = new MimeMessageHelper(msg);
            h.setFrom(mailProperties.getUsername());
            h.addTo(to);
            h.addCc(mailProperties.getUsername());
            h.setSubject("纯文本邮件发送测试");
            h.setText("使用Springboot-JvaMailSenderImpl工具类来发送文本邮件");
            mailSender.send(msg);
        }
    
        //发送html文本,不带图片
        @Test
        public void sendSimpleHtmlEmail() throws Exception {
            String to="[email protected]";
            MimeMessage msg = mailSender.createMimeMessage();
            MimeMessageHelper h = new MimeMessageHelper(msg);
            h.setFrom(mailProperties.getUsername());
            h.addTo(to);
            h.addCc(mailProperties.getUsername());
            h.setSubject("html文本邮件发送测试");
            String content="使用Springboot-JvaMailSenderImpl工具类来发送文本邮件" +
                    "<br>" +
                    "<h1>标题</h1>"+
                    "<div style='width:50%;height:100px;border:1px solid black'>我是div标签</div>";
            h.setText(content,true);
            mailSender.send(msg);
        }
    
        //发送html文本,带网络图片
        @Test
        public void sendSimpleHtmlEmailAndImg() throws Exception {
            String to="[email protected]";
            MimeMessage msg = mailSender.createMimeMessage();
            MimeMessageHelper h = new MimeMessageHelper(msg);
            h.setFrom(mailProperties.getUsername());
            h.addTo(to);
            h.addCc(mailProperties.getUsername());
            h.setSubject("html文本邮件发送带图片");
    
            //图片地址两种写法:网络图片;本地图片
            String content="<h1>使用Springboot-JvaMailSenderImpl工具类来发送文本邮件</h1>" +
                    "<div style='width:50%;height:100px;border:1px solid black'>我是div标签</div>" +
                    "<img  src='https://t7.baidu.com/it/u=1881842538,2998806722&fm=193&f=GIF'/>";
            h.setText(content,true);
            mailSender.send(msg);
        }
    
        //发送html文本,带本地图片
        @Test
        public void sendSimpleHtmlEmailAndImg2() throws Exception {
            String to="[email protected]";
            MimeMessage msg = mailSender.createMimeMessage();
            //支持文件上传
            MimeMessageHelper h = new MimeMessageHelper(msg,true);
            h.setFrom(mailProperties.getUsername());
            h.addTo(to);
            h.addCc(mailProperties.getUsername());
            h.setSubject("html文本邮件发送带图片");
    
            //图片地址两种写法:网络图片;本地图片
            String content="使用Springboot-JvaMailSenderImpl工具类来发送文本邮件" +
                    "<br>" +
                    "<div style='width:50%;height:100px;border:1px solid black'>我是div标签</div>" +
                    "<img src='cid:ei'/>";
            h.setText(content,true);
            //自动把本地图片上传的服务器,作为网络图片
            h.addInline("ei",new File("E:/test2.jpg"));
    
            mailSender.send(msg);
        }
    
        //发送html文本,带本地图片,带附件
        @Test
        public void sendSimpleHtmlEmailAndImg2AndAttach() throws Exception {
            String to="[email protected]";
            MimeMessage msg = mailSender.createMimeMessage();
            //支持文件上传
            MimeMessageHelper h = new MimeMessageHelper(msg,true);
            h.setFrom(mailProperties.getUsername());
            h.addTo(to);
            h.addCc(mailProperties.getUsername());
            h.setSubject("html文本邮件发送带图片");
    
            //图片地址两种写法:网络图片;本地图片
            String content="使用Springboot-JvaMailSenderImpl工具类来发送文本邮件" +
                    "<br>" +
                    "<div style='width:50%;height:100px;border:1px solid black'>我是div标签</div>" +
                    "<img style='width:50%;height:50%' src='cid:ei'/>";
            h.setText(content,true);
            //自动把本地图片上传的服务器,作为网络图片
            h.addInline("ei",new File("E:/test2.jpg"));
            File f = new File("E:/demo.txt");
            h.addAttachment(f.getName(),f);
    
            mailSender.send(msg);
        }
    }
    

    封装工具类

    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.springframework.boot.autoconfigure.mail.MailProperties;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.Resource;
    import javax.imageio.ImageIO;
    import javax.mail.MessagingException;
    import javax.mail.internet.MimeMessage;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    
    @Component
    public class EmailUtil {
    
        private final static Logger log = LogManager.getLogger(EmailUtil.class);
    
        @Resource
        private JavaMailSender mailSender;
        @Resource
        private MailProperties mailProperties;
    
        public void sendEmail(String email, String title, String count) {
            sendEmail(email, title, count, null);
        }
    
        public void sendEmail(String email, String title, String count, File... files) {
            MimeMessage msg = mailSender.createMimeMessage();
            MimeMessageHelper h = new MimeMessageHelper(msg);
            try {
                h.setFrom(mailProperties.getUsername());
                h.addTo(email);
                h.addCc(mailProperties.getUsername());
                h.setSubject(title);
                h.setText(count,true);
                if (files != null && files.length > 0) {
                    for (File f : files) {
                        //如果是图片,单独上传显示
                        if (isImage(f)) {
                            h.addInline("ei",f);
                        }
                        //图片也单独再上传为附件
                        h.addAttachment(f.getName(), f);
                    }
                }
                mailSender.send(msg);
            } catch (MessagingException e) {
                log.error(e);
            }
        }
    
        //判断文件是否是图片类型
        private boolean isImage(File file) {
            try {
                Image image = ImageIO.read(file);
                return image != null;
            } catch (IOException e) {
                return false;
            }
        }
    }

    使用thymeleaf引擎重置密码邮件

  • 添加thymeleaf启动器

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 在templates目录下添加html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>点击如下链接重置密码,此链接有效期10分钟,如过期,请回到主页重新点击忘记密码!</h3>
<h3 th:text="${参数名}"></h3>
<!--服务端页面;前端vue页面-->
<a th:href="@{http://localhost:8080/resetpwd(t=${token})}">点我重置</a>
</body>
</html>
  • 使用Thymeleaf引擎对象解析resetPwdEmail.html模板

@Resource
private TemplateEngine engine;

//基于thymeleaf模板引擎,解析html模板,生成html文本,
@Test
public void sendSimpleHtmlEmail2() throws Exception {
  Context c = new Context();
  c.setVariable("参数名","值");
  c.setVariable("token", "xxxxxxx");
  String html = engine.process("html文件名", c);
}
  • 把解析后的html字符串发送指定邮箱即可

标签:String,重置,new,thymeleaf,html,mail,msg,import,邮件
From: https://blog.csdn.net/2201_75365850/article/details/140442980

相关文章

  • 邮件地址搜索软件_邮件地址采集软件
    一款搜索邮件地址和手机号码的软件,可以按整站搜索,也可以按关键词搜索关键词搜索支持baiu.com和bing.com。界面简单,使用方法非常简易和方便。易邮件地址搜索大师特色—易邮件地址搜索大师是一款搜索邮件地址和手机号码的软件,可以按整站搜索,也可以按关键词搜索。使用方法非常......
  • 基于SpringBoot+Vue+uniapp的邮件过滤系统的详细设计和实现(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus系统测试系统测试目的系统功能测试系统测试结论为什么选择我代码参考数据库参考源码获取前言......
  • Exchange邮箱用户发邮件失败,提示“ Client does not have permissions to send as thi
    原贴https://www.cnblogs.com/dreamer-fish/p/16876232.htmlExchange邮箱用户发邮件失败,提示“Clientdoesnothavepermissionstosendasthissender”Exchange用户发邮件提示“5505.7.60SMTP;Clientdoesnothavepermissionstosendasthissender”处理方法:......
  • 使用Docker部署mailcow开源邮件系统详细过程
    1.项目介绍项目网站:mailcow:dockerized–Blog根据官方介绍,这个项目名称是mailcow,名称都是小写的。下面内容是通过AI翻译自官方文档:mailcow:dockerizeddocumentationmailcow:dockerized是一个基于Docker的开源组件/电子邮件套件。mailcow依赖于许多广为人知且长期......
  • 重置 RedHat 9 root 账户密码
    重置RedHat9root账户密码​​‍​​​​‍​touch/.autorelable​是第一种方式​​‍​fixfiles-Fonboot​是第二种方式:​​‍退出重启系统:​​‍​​......
  • 钓鱼邮件演练——筑牢企业安全防线的新篇章
    在信息爆炸的时代,网络安全已经成为企业和组织不可忽视的重要议题。尤其是钓鱼邮件,作为网络犯罪中最常见的手法之一,不仅能够窃取敏感信息,还可能引发连锁反应,对企业造成巨大的经济损失和声誉损害。中国联通国际公司深刻理解这一挑战,为此推出了一款专为企业设计的“钓鱼邮件演练”产......
  • Contact Form联系表单自动发送邮件(超级简单)
    前几天发现了aoksend推出的这个联系表单的组件,非常好用,只有一个php文件,把php文件放到网站主目录里面。然后去aoksend注册和配置好域名和发信邮箱,可以得到发送密钥:app_key,然后配置好邮件模板,可以得到邮件id:template_id。将这两个数据配置到上面那个php文件里面第31行的位置。$d......
  • layui js thymeleaf 公共工具类
    layuijsthymeleaf公共工具类其中功能包括:普通表格渲染树形表格渲染普通编辑(添加/删除/编辑)更多编辑(添加/编辑/更多)上传图片constcommon={getTable(table,url,cols,condition){if(!condition||condition==''){condition=......
  • 【每天认识一个漏洞】spf邮件伪造漏洞
    ......
  • 重置DedeCMS系统管理员账号与密码
    DedeCMS 系统的管理员账号与密码都是存储在数据库中的。如果发生密码丢失或其它情况,我们可以通过重写数据库(数据表)的方式来重置 DedeCMS 的账号与密码。如此操作的前置条件是可以登录并管理数据库。如果没有或拿不到数据库的管理权限,那就行不通了。第一步:登录数据库​如果是......