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

邮件发送

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

  @Test
    public void sendEmail(){
        String account="19008239181@163.com";
        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="chengdujavasm@126.com";
        //会话对象
        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: 19937782588@163.com
        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="chengdujavasm@126.com";
            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="chengdujavasm@126.com";
            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="chengdujavasm@126.com";
            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="chengdujavasm@126.com";
            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="chengdujavasm@126.com";
            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字符串发送指定邮箱即可

  • 22
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Thymeleaf模板引擎来发送邮件。以下是一个示例代码,演示了如何使用Thymeleaf生成HTML内容,并将其作为电子邮件正文发送。 首先,确保在您的项目中添加了ThymeleafJavaMail依赖项。在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 接下来,创建一个简单的Thymeleaf模板,例如email-template.html,将其放置在classpath:/templates目录下: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Email Template</title> </head> <body> <h1>Hello, [[${name}]]!</h1> <p>Thank you for subscribing to our newsletter.</p> </body> </html> ``` 然后,创建一个类来处理邮件发送逻辑: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.IOException; import java.nio.charset.StandardCharsets; @Component public class EmailService { @Autowired private JavaMailSender emailSender; @Autowired private TemplateEngine templateEngine; public void sendEmail(String recipientEmail, String recipientName) throws MessagingException, IOException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, StandardCharsets.UTF_8.name()); // 设置邮件主题 helper.setSubject("Welcome to our newsletter"); // 设置邮件发送者 helper.setFrom("your-email@example.com"); // 设置邮件接收者 helper.setTo(recipientEmail); // 创建Thymeleaf上下文 Context context = new Context(); context.setVariable("name", recipientName); // 使用Thymeleaf模板生成HTML内容 String htmlContent = templateEngine.process("email-template", context); // 设置邮件内容 helper.setText(htmlContent, true); // 发送邮件 emailSender.send(message); } } ``` 在这个示例中,EmailService类使用JavaMailSender和TemplateEngine来发送邮件。首先,它创建一个MimeMessage对象,并使用MimeMessageHelper来设置邮件的基本属性,如主题、发件人和收件人。 然后,它创建一个Thymeleaf的上下文对象,并将收件人的姓名作为变量传递给模板。接下来,它使用TemplateEngine的process方法将模板与上下文结合,生成HTML内容。 最后,它调用MimeMessageHelper的setText方法,将HTML内容设置为邮件的正文,并使用JavaMailSender发送邮件。 请注意,您需要使用您自己的发件人邮箱地址替换"your-email@example.com"。 这只是一个基本示例,您可以根据项目的需要进行自定义和扩展。希望这能帮助到您!如果您有更多的问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值