【Java Web】发送邮件 Spring Mail+Thymeleaf

1. 邮箱启用SMTP服务

生成授权码,然后看一下发送邮件服务器及端口。

2. Spring Mail

2.1 在pom中导入jar包
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
			<version>2.1.5.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.6.2</version>
		</dependency>
2.2 邮箱参数设置
# MailProperties
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=123456789@qq.com
spring.mail.password=xxxxxxxxxxxx
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
2.3 使用JavaMailSender发送邮件,建立mailClient.java工具类
package com.nowcoder.community.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class MailClient {

    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

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

    public void sendMail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("发送邮件失败:" + e.getMessage());
        }
    }

}

2.4 发邮件测试单元
package com.nowcoder.community;

import com.nowcoder.community.util.MailClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.Thymeleaf;
import org.thymeleaf.context.Context;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {

    @Autowired
    private MailClient mailClient;


    @Test
    public void testTextMail() {
        mailClient.sendMail("接收邮箱@qq.com", "TEST", "Welcome.");
    }



}

3.模板引擎

在测试类中注入模板引擎,使用testHtmlMail方法发送html类型邮件。如果没有收到邮件,一般可以在垃圾箱中找到。

@Autowired
private TemplateEngine templateEngine;
@Test
    public void testHtmlMail(){
        Context context = new Context();
        context.setVariable("username","sunday");

        String content = templateEngine.process("/mail/demo", context);
        System.out.println(content);

        mailClient.sendMail("xxxxxx@mails.ucas.ac.cn", "Html", content);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是使用Spring Boot和Thymeleaf实现拦截器的步骤: 1.创建一个拦截器类,该类需要实现HandlerInterceptor接口。在该类中,您可以实现三个方法:preHandle,postHandle和afterCompletion。这些方法分别在处理程序执行之前,之后和完成之后调用。 ```java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 在请求处理之前进行调用(Controller方法调用之前) System.out.println("请求处理之前调用……"); return true; // 如果返回false,则请求中断 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后) System.out.println("请求处理之后调用……"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 在视图被渲染之后调用(主要用于资源清理工作) System.out.println("视图渲染之后调用……"); } } ``` 2.将拦截器注册到应用程序中。在Spring Boot应用程序中,您可以通过使用WebMvcConfigurerAdapter类来注册拦截器。在该类中,您可以重写addInterceptors方法,并将您的拦截器添加到拦截器链中。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebAppConfiguration extends WebMvcConfigurerAdapter { @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor); } } ``` 3.使用Thymeleaf进行视图渲染。在您的控制器方法中,您可以返回一个包含视图名称和模型对象的ModelAndView对象。在视图中,您可以使用Thymeleaf模板来渲染HTML内容。在下面的示例中,我们将使用layout.html作为页面布局,并使用th:replace指令将内容注入到该布局中。 ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>My Page</title> </head> <body> <div th:replace="layout :: content"> <h1 th:text="${message}">Hello, World!</h1> </div> </body> </html> ``` 4.创建一个包含布局的Thymeleaf模板。在该模板中,您可以定义页面的基本结构和样式,并使用th:fragment指令定义页面的各个部分。在下面的示例中,我们将使用layout.html作为页面布局,并使用th:fragment指令定义页面的内容部分。 ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title th:text="${pageTitle}">My Site</title> </head> <body> <div th:fragment="content"></div> </body> </html> ``` 以上就是使用Spring Boot和Thymeleaf实现拦截器的步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值