採用經典「表單頁 + 處理頁」模式:前端 message.jsp 收集用戶輸入,後端 message_do.jsp 使用 JavaMail API 經由 SMTP 發送郵件。示例使用 Sohu 郵箱服務器,實際部署時請替換為企業郵箱或第三方郵件服務(SendGrid、阿里雲郵件推送等)。
<form action="message_do.jsp" method="post">
<table>
<tr><td>信件標題:*</td><td><input name="topic" required></td></tr>
<tr><td>反饋信息:*</td><td><textarea name="body" rows="5" required></textarea></td></tr>
<tr><td>稱呼:*</td><td><input name="name" required></td></tr>
<tr><td>郵箱:*</td><td><input name="email" type="email" required></td></tr>
<tr><td>電話:</td><td><input name="phone"></td></tr>
<tr><td>公司/網址:</td><td><input name="http"></td></tr>
<tr><td colspan="2"><input type="submit" value="提交" onclick="return check()"></td></tr>
</table>
</form>
<%@ page import="javax.mail.*,javax.mail.internet.*,javax.activation.*,java.util.Properties" %>
<%
String to = "admin@example.com"; // 接收方,可從數據庫讀取
String from = "noreply@yourdomain.com";
String host = "smtp.yourdomain.com";
String user = "noreply@yourdomain.com";
String pass = "your_password";
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.ssl.enable", "true"); // SSL 加密
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
msg.setSubject("網站留言: " + request.getParameter("topic"));
msg.setSentDate(new Date());
String content = "姓名: " + request.getParameter("name") + "\n"
+ "郵箱: " + request.getParameter("email") + "\n"
+ "電話: " + request.getParameter("phone") + "\n"
+ "公司: " + request.getParameter("http") + "\n\n"
+ request.getParameter("body");
msg.setText(content);
Transport.send(msg);
out.println("<script>alert('發送成功');location.href='message.jsp';</script>");
} catch (MessagingException e) {
e.printStackTrace();
out.println("發送失敗: " + e.getMessage());
}
%>
mail.smtp.ssl.enable=true 並使用 465 或 587 端口。535 Authentication failed:檢查賬號/密碼、是否開啟 SMTP 服務、是否需授權碼而非登入密碼。Could not connect to SMTP host:檢查防火牆、安全組、端口通達性;嘗試 telnet smtp.host 465。