来实现。

首先,需要添加相关的依赖,包括spring-boot-starter-mail和thymeleaf。

pom.xml文件:

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

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

接下来创建一个邮件发送工具类:

@Service
public class MailService {

    @Autowired
    private JavaMailSender mailSender;

    public void sendMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        mailSender.send(message);
    }
}

这里使用了JavaMailSender来发送邮件,并且使用了Thymeleaf来渲染邮件内容。

接下来在application.properties中配置SMTP:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email-address
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

注意要替换成自己的邮箱地址和密码。

最后,在Controller中调用邮件发送工具类:

@Controller
public class MailController {

    @Autowired
    private MailService mailService;

    @GetMapping("/sendMail")
    public String sendMail() throws MessagingException {
        String to = "recipient@example.com";
        String subject = "Test Mail";
        String content = "<p>This is a test mail.</p>";
        mailService.sendMail(to, subject, content);
        return "success";
    }
}

这里使用了@GetMapping注解来处理请求,并且调用了MailService的sendMail方法来发送邮件。

最后,在Thymeleaf模板中添加一个按钮来触发发送邮件的操作:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Send Mail</title>
</head>
<body>
    <button onclick="sendMail()">Send Mail</button>
    <script>
        function sendMail() {
            window.location.href = "/sendMail";
        }
    </script>
</body>
</html>

这里使用了JavaScript来实现点击按钮后发送请求的功能。当用户点击按钮时,会调用sendMail函数,然后跳转到/sendMail路径,触发Controller中的sendMail方法,从而发送邮件

spring boot编写一个发送邮件工具类并进行SMTP配置controller调用工具类并将发送邮件信息写到action中前端只有一个button按钮点击发送即可前端用thymeleaf

原文地址: https://www.cveoy.top/t/topic/goCW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录