编写一个发送邮件的工具类后端用spring boot前端用thyme leaf
以下是一个简单的发送邮件的工具类,用于后端使用spring boot框架,前端使用thymeleaf模板引擎:
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender;
public void sendMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
}
在这个工具类中,我们使用了Spring Boot提供的JavaMailSender来发送邮件。该类可以通过在application.properties文件中配置来进行配置。例如:
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
在这个例子中,我们使用了Gmail作为邮件服务器,并且需要提供你的邮箱地址和密码来进行验证。我们还启用了SMTP的身份验证和TLS加密,以确保邮件的安全性。
在前端使用thymeleaf模板引擎时,我们可以通过在Controller中注入MailService来调用sendMail方法来发送邮件。例如:
@Controller
public class MyController {
@Autowired
private MailService mailService;
@PostMapping("/sendMail")
public String sendMail(@RequestParam String to, @RequestParam String subject, @RequestParam String content) {
mailService.sendMail(to, subject, content);
return "mailSent.html";
}
}
在这个例子中,我们创建了一个POST请求的路由,接收三个参数:收件人的邮箱地址、邮件的主题和内容。我们在Controller中注入了MailService,并在方法中调用它的sendMail方法来发送邮件。最后,我们返回一个HTML模板来显示邮件发送成功的消息。
在前端的HTML模板中,我们可以使用thymeleaf的语法来渲染页面,并使用表单来提交邮件的信息。例如:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>发送邮件</title>
</head>
<body>
<h1>发送邮件</h1>
<form action="/sendMail" method="post">
<label for="to">收件人:</label>
<input type="email" id="to" name="to" required><br><br>
<label for="subject">主题:</label>
<input type="text" id="subject" name="subject" required><br><br>
<label for="content">内容:</label>
<textarea id="content" name="content" required></textarea><br><br>
<button type="submit">发送</button>
</form>
</body>
</html>
在这个例子中,我们使用了thymeleaf的命名空间来定义th前缀,并在HTML标签中使用了它的语法来绑定表单的数据。当用户提交表单后,将调用MyController中的sendMail方法,并将邮件发送到指定的收件人。最后,我们返回一个HTML模板,用于显示邮件发送成功的消息
原文地址: https://www.cveoy.top/t/topic/fHix 著作权归作者所有。请勿转载和采集!