Java Spring Boot 发送电子邮件 - 使用 Thymeleaf 模板引擎
以下是一个简单的发送电子邮件的工具类,使用了 JavaMail 和 Spring Boot 框架:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailUtil {
private static final String EMAIL_USERNAME = 'your-email-username';
private static final String EMAIL_PASSWORD = 'your-email-password';
private static final String EMAIL_HOST = 'smtp.your-email-provider.com';
private static final int EMAIL_PORT = 587;
public static void sendEmail(String recipient, String subject, String content) throws MessagingException {
Properties props = new Properties();
props.put('mail.smtp.auth', 'true');
props.put('mail.smtp.starttls.enable', 'true');
props.put('mail.smtp.host', EMAIL_HOST);
props.put('mail.smtp.port', EMAIL_PORT);
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(EMAIL_USERNAME, EMAIL_PASSWORD);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(EMAIL_USERNAME));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(content);
Transport.send(message);
}
}
在 Spring Boot 应用程序中使用此工具类,您可以创建一个控制器来处理发送电子邮件的请求。以下是一个简单的示例:
import javax.mail.MessagingException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class EmailController {
@PostMapping('/send-email')
public String sendEmail(@RequestParam('recipient') String recipient,
@RequestParam('subject') String subject,
@RequestParam('content') String content) {
try {
EmailUtil.sendEmail(recipient, subject, content);
return 'email-sent';
} catch (MessagingException e) {
e.printStackTrace();
return 'email-send-error';
}
}
}
此控制器处理 POST 请求,其中包含收件人地址,主题和内容参数。在方法中,使用 EmailUtil 类发送电子邮件。如果发送成功,则返回 'email-sent' 视图,否则返回 'email-send-error' 视图。此视图可以使用 Thymeleaf 模板引擎渲染。例如:
<!DOCTYPE html>
<html xmlns:th='http://www.thymeleaf.org'>
<head>
<meta charset='UTF-8'>
<title>Email Sent</title>
</head>
<body>
<h1>Email Sent</h1>
<p>Your email has been sent successfully.</p>
</body>
</html>
在此示例中,Thymeleaf 使用 th 命名空间来引用模板引擎。在 <h1> 和 <p> 标签中,使用 Thymeleaf 表达式来呈现文本。
原文地址: https://www.cveoy.top/t/topic/omVW 著作权归作者所有。请勿转载和采集!