萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 發送郵件完整實例:從表單提交到 JavaMail 實戰

整體架構

採用經典「表單頁 + 處理頁」模式:前端 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());
}
%>

關鍵最佳實踐

  1. 啟用 SSL/TLS:現代 SMTP 服務器強制加密,務必設置 mail.smtp.ssl.enable=true 並使用 465 或 587 端口。
  2. 異步發送:生產環境切勿在請求線程中同步發送,應放入消息隊列或線程池異步處理,避免阻塞響應。
  3. 參數校驗與防注入:前後端雙重校驗,防止郵件頭注入攻擊(過濾換行符)。
  4. 錯誤重試與日誌:記錄發送失敗詳情,配合死信隊列重試。
  5. 憑證管理:密碼勿硬編碼,使用配置中心或密鑰管理服務。

常見問題排查

  • 535 Authentication failed:檢查賬號/密碼、是否開啟 SMTP 服務、是否需授權碼而非登入密碼。
  • Could not connect to SMTP host:檢查防火牆、安全組、端口通達性;嘗試 telnet smtp.host 465。
  • 郵件進垃圾箱:配置 SPF/DKIM/DMARC,優化內容質量,避免營銷詞彙過度。
copyright © 萬盛學電腦網 all rights reserved