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

JavaMail 發送郵件簡易範例:JavaBean 版本

     編輯:關於JSP

SimpleSendMessage.java

package com.example.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SimpleSendMessage {
    public static void main(String[] args) {
        String host = "server.myhost.com";
        String to = "YourFriend@somewhere.com";
        String from = "MeMeMe@myhost.com";
        String subject = "JSP Rules!";
        String messageText = "I am sending a message using the JavaMail API.\nI can include any text that I want.";
        boolean sessionDebug = false;

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

        try {
            Message msg = new MimeMessage(session);
            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);
            System.out.println("郵件發送成功");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

關鍵點說明

  • Session.getDefaultInstance(props, null):無驗證器版本;若 SMTP 需認證,改用 Session.getInstance(props, new Authenticator(){...})。
  • props.put("mail.smtp.auth", "true") 啟用認證。
  • MimeMessage 支援 HTML 內容:msg.setContent(html, "text/html;charset=UTF-8")。
  • 附件處理:建立 MimeMultipart,加入 MimeBodyPart 並 attachFile()。
  • 非同步發送:生產環境建議放入工作佇列(如 ExecutorService、JMS),避免阻塞請求執行緒。

部署注意

  • 需 mail.jar、activation.jar (Java 6+ 已內建) 放入 WEB-INF/lib。
  • 測試時確認防火牆開放 SMTP 埠 (25/465/587)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved