首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JavaMail 發送郵件後端處理:JSP 版本

     編輯:關於JSP

MailExample.jsp

<%@ page import="java.util.*, javax.mail.*, javax.mail.internet.*, javax.activation.*" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<html><head><title>郵件發送結果</title></head><body>
<%
    String host = "yourmailhost"; // 需替換為真實 SMTP 主機
    String to = request.getParameter("to");
    String from = request.getParameter("from");
    String subject = request.getParameter("subject");
    String messageText = request.getParameter("body");

    Properties props = System.getProperties();
    props.put("mail.host", host);
    props.put("mail.transport.protocol", "smtp");
    Session mailSession = Session.getDefaultInstance(props, null);
    mailSession.setDebug(false);

    Message msg = new MimeMessage(mailSession);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress(to)});
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setText(messageText);
    Transport.send(msg);

    out.println("郵件已發送給 " + to);
    out.println("
寄件人: " + from); out.println("
SMTP 主機: " + host + "."); %> </body></html>

改進版本建議

  • 輸入驗證:檢查 to/from 格式、subject/body 非空、長度限制。
  • 例外處理:try-catch MessagingException 友善提示錯誤(如主機不可達、認證失敗、地址拒收)。
  • 編碼設定:msg.setSubject(subject, "UTF-8")、msg.setText(messageText, "UTF-8") 確保中文正常。
  • SMTP 認證:若主機需認證,改用 Session.getInstance(props, new Authenticator(){...})。
  • MVC 分離:邏輯移至 Servlet/Service,JSP 僅顯示結果。

完整發送流程圖

mailform.html (GET) → 填寫表單 → POST → MailExample.jsp (處理發送) → 顯示結果
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved