簡單講述下發送和接受郵件的協議:
SMTP

    簡單郵件傳輸協議(Simple Mail Transfer Protocol,SMTP)由 RFC 821 定義。它定義了發送電子郵件的機制。在 JavaMail API 環境中,您基于 JavaMail 的程序將和您的公司或因特網服務供應商的(Internet Service Provider's,ISP's)SMTP 服務器通信。SMTP 服務器會中轉消息給接收方 SMTP 服務器以便最終讓用戶經由 POP 或 IMAP 獲得。這不是要求 SMTP 服務器成為開放的中繼,盡管 SMTP 服務器支持身份驗證,不過還是得確保它的配置正確。像配置服務器來中繼消息或添加刪除郵件賬號這類任務的實現,JavaMail API 中并不支持。

   
POP

    POP 代表郵局協議(Post Office Protocol)。目前用的是版本 3,也稱 POP3,RFC 1939 定義了這個協議。POP 是一種機制,因特網上大多數人用它得到郵件。它規定每個用戶一個郵箱的支持。這就是它所能做的,而這也造成了許多混淆。使用 POP 時,用戶熟悉的許多性能并不是由 POP 協議支持的,如查看有幾封新郵件消息這一性能。這些性能內建于如 Eudora 或 Microsoft Outlook 之類的程序中,它們能記住一些事,諸如最近一次收到的郵件,還能計算出有多少是新的。所以當使用 JavaMail API 時,如果您想要這類信息,您就必須自己算。

IMAP

    IMAP 是更高級的用于接收消息的協議。在 RFC 2060 中被定義,IMAP 代表因特網消息訪問協議(Internet Message Access Protocol),目前用的是版本 4,也稱 IMAP4。在用到 IMAP 時,郵件服務器必需支持這個協議。不能僅僅把使用 POP 的程序用于 IMAP,并指望它支持 IMAP 所有性能。假設郵件服務器支持 IMAP,基于 JavaMail 的程序可以利用這種情況 — 用戶在服務器上有多個文件夾(folder),并且這些文件夾可以被多個用戶共享。

因為有這一更高級的性能,您也許會認為所有用戶都會使用 IMAP。事實并不是這樣。要求服務器接收新消息,在用戶請求時發送到用戶手中,還要在每個用戶的多個文件夾中維護消息。這樣雖然能將消息集中備份,但隨著用戶長期的郵件夾越來越大,到磁盤空間耗盡時,每個用戶都會受到損失。使用 POP,就能卸載郵件服務器上保存的消息了。

MIME

    MIME 代表多用途因特網郵件擴展標準(Multipurpose Internet Mail Extensions)。它不是郵件傳輸協議。但對傳輸內容的消息、附件及其它的內容定義了格式。這里有很多不同的有效文檔:RFC 822RFC 2045RFC 2046RFC 2047。作為一個 JavaMail API 的用戶,您通常不必對這些格式操心。無論如何,一定存在這些格式而且程序會用到它。

NNTP 及其它

   因為 JavaMail API 將供應商和所有其它的東西分開了,您就能輕松添加額外的協議支持。Sun 保留了一張第三方供應商列表,他們利用了 Sun 不提供超出(out-of-the-box)支持范圍的協議。您會找到 NNTP(網絡新聞傳輸協議)[新聞組]、S/MIME(安全多用途因特網郵件擴展)及其它支持。

接下來,主要講下:SMTP的模型 
     SMTP提供了一種郵件傳輸的機制,當收件方和發件方都在一個網絡上時,可以把郵件直傳給對方;當雙方不在同一個網絡上時,需要通過一個或幾個中間服務器轉發。SMTP首先由發件方提出申請,要求與接收方SMTP建立雙向的通信渠道,收件方可以是最終收件人也可以是中間轉發的服務器。收件方服務器確認可以建立連接后,雙發就可以開始通信。下面是SMTP的模型示意圖。



發件方SMTP向收件方發處MAIL命令,告知發件方的身份;如果收件方接受,就會回答OK。發件方再發出RCPT命令,告知收件人的身份,收件方SMTP確認是否接收或轉發,如果同意就回答OK;接下來就可以進行數據傳輸了。通信過程中,發件方SMTP與收件方SMTP 采用對話式的交互方式,發件方提出要求,收件方進行確認,確認后才進行下一步的動作。整個過程由發件方控制,有時需要確認幾回才可以。



為了保證回復命令的有效,SMTP要求發件方必須提供接收方的服務器及郵箱。郵件的命令和答復有嚴格的語法定義,并且回復具有相應的數字代碼。所有的命令由ASCII碼組成。命令代碼是大小寫無關的,如MAIL和 mail ﹑mAIL是等效的。

2. SMTP的基本命令
SMTP定義了14個命令,它們是:

HELO
MAIL FROM:
RCPT TO:
DATA
RSET
SEND FROM:
SOML FROM:
SAML FROM:
VRFY
EXPN
HELP [ ]
NOOP
QUIT
TURN
其中使得SMTP工作的基本的命令有7個,分別為:HELO﹑MAIL﹑RCPT﹑DATA﹑REST﹑NOOP和QUIT.下面分別介紹如下。

HELO--發件方問候收件方,后面是發件人的服務器地址或標識。收件方回答OK時標識自己的身份。問候和確認過程表明兩臺機器可以進行通信,同時狀態參量被復位,緩沖區被清空。

MAIL--這個命令用來開始傳送郵件,它的后面跟隨發件方郵件地址(返回郵件地址)。它也用來當郵件無法送達時,發送失敗通知。為保證郵件的成功發送,發件方的地址應是被對方或中間轉發方同意接受的。這個命令會清空有關的緩沖區,為新的郵件做準備。

RCPT --這個命令告訴收件方收件人的郵箱。當有多個收件人時,需要多次使用該命令,每次只能指明一個人。如果接收方服務器不同意轉發這個地址的郵件,它必須報550錯誤代碼通知發件方。如果服務器同意轉發,它要更改郵件發送路徑,把最開始的目的地(該服務器)換成下一個服務器。

DATA--收件方把該命令之后的數據作為發送的數據。數據被加入數據緩沖區中,以單獨一行是"."的行結束數據。結束行對于接收方同時意味立即開始緩沖區內的數據傳送,傳送結束后清空緩沖區。如果傳送接受,接收方回復OK。

REST--這個命令用來通知收件方復位,所有已存入緩沖區的收件人數據,發件人數據和待傳送的數據都必須清除,接收放必須回答OK.

NOOP--這個命令不影響任何參數,只是要求接收放回答OK, 不會影響緩沖區的數據。

QUIT--SMTP要求接收放必須回答OK,然后中斷傳輸;在收到這個命令并回答OK前,收件方不得中斷連接,即使傳輸出現錯誤。發件方在發出這個命令并收到OK答復前,也不得中斷連接。

下面是SMTP答復中用到的代碼和含義:

500 Syntax error, command unrecognized
[This may include errors such as command line too long]
501 Syntax error in parameters or arguments
502 Command not implemented
503 Bad sequence of commands
504 Command parameter not implemented
211 System status, or system help reply
214 Help message
[Information on how to use the receiver or the meaning of a
particular non-standard command; this reply is useful only to the human user]
220 Service ready
221 Service closing transmission channel
421 Service not available, closing transmission channel
[This may be a reply to any command if the service knows it must shut down]
250 Requested mail action okay, completed
251 User not local; will forward to
450 Requested mail action not taken: mailbox unavailable
[E.g., mailbox busy]
550 Requested action not taken: mailbox unavailable
[E.g., mailbox not found, no access]
451 Requested action aborted: error in processing
551 User not local; please try
452 Requested action not taken: insufficient system storage
552 Requested mail action aborted: exceeded storage allocation
553 Requested action not taken: mailbox name not allowed
[E.g., mailbox syntax incorrect]
354 Start mail input; end with .
554 Transaction failed
最后,讓我們看一個RFC821中給出的例子。這封信是Smith在主機Alpha.ARPA 發給主機Beta.ARPA上的
Jones,Green和 Brown.并且假定兩臺主機在同一個網絡上。

S: MAIL FROM:
R: 250 OK
S: RCPT TO:
R: 250 OK
S: RCPT TO:
R: 550 No such user here
S: RCPT TO:
R: 250 OK
S: DATA
R: 354 Start mail input; end with .
S: Blah blah blah...
S: ...etc. etc. etc.
S: .
R: 250 OK
郵件最后被對方接受。


◆ 電子郵件的工作原理


電子郵件與普通郵件有類似的地方,發信者注明收件人的姓名與地址(即郵件地址),發送方服務器把郵件傳到收件方服務器,收件方服務器再把郵件發到收件人的郵箱中。如下圖所示:



更進一步的解釋涉及到以下幾個概念:

MUA -- Mail User Agent, 郵件用戶代理,幫助用戶讀寫郵件;

MTA -- Mail Transport Agent, 郵件傳輸代理,負責把郵件由一個服務器傳到另一個服務

器或郵件投遞代理;

MDA -- Mail Delivery Agent, 郵件投遞代理,把郵件放到用戶的郵箱里。

整個郵件傳輸過程如下:

目前使用的SMTP 協議是存儲轉發協議,意味著它允許郵件通過一系列的服務器發送到最終目的地。服務器在一個隊列中存儲到達的郵件,等待發送到下一個目的地。下一個目的地可以是本地用戶,或者是另一個郵件服務器,如下圖所示。



如果下游的服務器暫時不可用,MTA 就暫時在隊列中保存信件,并在以后嘗試發送。



◆ 電子郵件的信頭結構及分析

1 .郵件的結構
在最高層,郵件的結構是非常簡單的,用戶從終端機上看到的郵件格式一般為:

1. From:
user1@domain1.com

2. To:
user2@domain2.com

3. Subject: Explaination of mail format

4. Date: Thu, 1 Apr 1999. 10:00:00 GMT

5. Hi, Jack

7. This mail is to explain you the mail format

8. - - - -

9. Thanks

10. Bob

其中, 1~~4 行稱作信件信頭(message header) 6~~10行描述信件要表達的內容,稱為信體 (message body)。第5行是空行,根據RFC822的要求,信頭和信體之間必須加入一空行。[i]信頭通常包含字段From, To, Subject 和Date,有的郵件還包含cc,bcc等字段。

2. 郵件的信頭

事實上,郵件在傳輸過程中,服務器要把它打包成一個數據對象,包括上面的信件和一個信封。郵件的投遞是依靠信封上的地址或信封信頭(envelop address 或envelop header),而不是上面講的信件上的地址。

從表面上看,一封郵件是從發件人的機器直接傳送到收件人的機器,但通常這并不正確,一封郵件發送和接受過程至少要經過四臺計算機。參考下圖所示。用戶通常在自己的電腦前編寫閱讀郵件,我們把它叫做客戶端 (client 1~~4 )。大部分組織里,都是用一臺專門的機器處理郵件,稱作郵件服務器 (SMTP1, SMTP2). 如果用戶是從家里撥號上網,那末郵件服務器是ISP 提供的。



當某個用戶在自己的電腦 Client1 前編寫完一個郵件,然后把它發送到他的ISP 的郵件服務器SMTP1。此時她的機器已經完成了所有的工作,但郵件服務器SMTP1還必須想法把郵件發送到目的地。SMTP1 通過閱讀信頭或信封上的地址,找到收件認得郵件服務器SMTP2, 然后與該服務器建立連接,把郵件發到收件人的服務器上,等待收件人來取閱。

下面我們將通過一個例子說明整個郵件傳送過程及郵件的信頭變化。假設發件人的名字叫 Sender, email地址是
sender@domain1.com使用的電腦名字叫 client1, IP 地址是 [111.11.1.1] (假設的地址)。 收件人的名字叫 receipt, email 地址是 receipt@domain2.com, 使用的電腦的名字叫 client2,IP 地址是 [222.22.2.2] (假設的地址)。當郵件編輯完傳送給其郵件服務器mail.domain1.com 時,郵件的信頭格式為:

From:
sender@domain1.com

To:
receipt@domain2.com

Date: Tue, Mar 18 1998 15:36:24 GMT

X-mailer:Sendmail 8.9.0

Subject: Greetings

當郵件服務器 mail.domain1.com 把郵件傳到接收方的服務器 mail.domain2.com 時,接受方服務器會在信頭上記錄下有關的計算機信息,郵件的信頭變成:

Received: from client1.domain1.com (client1.domain1.com [111.11.1.1]) by mail.domain1.com (8.8.5) id 004A21; Tue, Mar 18 1998 15:3 7:24 GMT

From:
sender@domain1.com

To:
receipt@domain2.com

Date: Tue, Mar 18 1998 15:36:24 GMT

Message-Id:

X-mailer:Sendmail 8.9.0

Subject: Greetings

當收件人服務器mail.domain2.com 把郵件接收并存初下來,等待收件人來閱讀時,郵件的信頭將會再加入一條記錄:

Received: from mail.domain1.com (mail.domain1.com [111.11.1.0] ) by mail.domain2.com (8.8.5/8.7.2) with ESMTP id LAA20869; Tue, Mar 18 1998 15:39:44 GMT

Received: from client1.domain1.com (client1.domain1.com [111.11.1.1]) by mail.domain1.com (8.8.5) id 004A21; Tue, Mar 18 1998 15:37:24 GMT

From:
sender@domain1.com

To:
receipt@domain2.com

Date: Tue, Mar 18 1998 15:36:24 GMT

Message-Id:

X-mailer:Sendmail 8.9.0

Subject: Greetings

上面整個記錄就將是收件人看到的完整的郵件信頭。讓我們逐行看一下信頭中各行的含義:

Received: from mail.domain1.com (mail.domain1.com [111.11.1.0] ) by mail.domain2.com (8.8.5/8.7.2) with ESMTP id LAA20869; Tue, Mar 18 1998 15:39:44 GMT

這封信是從一臺自稱為 mail.domain1.com 的機器上接收的;這臺機器的IP 地址是[111.11.1.0],真實名字就是標稱名字 mail.domain1.com; 接收方的機器名稱是 mail.domain2.com, 運行的郵件服務器是 Sendmail, 版本(8.8.5/8.7.2) 。接收方機器給郵件的編號是ESMTP id LAA20869, 接收到的時間是 Tue, Mar 18 1998 15:39:44 GMT。

Received: from client1.domain1.com (client1.domain1.com [111.11.1.1]) by mail.domain1.com (8.8.5) id 004A21; Tue, Mar 18 1998 15:37:24 GMT

這條記錄表明信件是由機器client1.domain1.com ( IP 地址是 [111.11.1.1]) 在Tue, Mar 18 1998 15:37:24 GMT交給mail.domain1.com,并賦給編號id 004A21。

From,TO ,Date和Subject 都易于理解,分別指明發件人,收件人,信件編輯日期及信件主題。

Message-Id:

這是由發件方郵件服務器賦給這封郵件的編號。與其它編號不同,這個編號自始至終跟隨郵件。


------------------------------------

方法一:沒有使用JavaMail API,而是根據SMTP協議的要求直接處理協議的細節發送郵件。
MailMessage.java

----------------------------------------

//這個類其實就是一個基本的JavaBean,用于完成一些基本信息的設置,也可以不要這個東西,直接在程序中寫明就可以,不過這樣條理較清楚一些,而且修改也方便一些.

  1package mail;
  2
  3public class MailMessage {
  4 
  5 private String from;
  6 private String to;
  7 private String datafrom;
  8 private String datato;
  9 private String subject;
 10 private String content;
 11 private String date;
 12 private String user;
 13 private String password;
 14
 15 public String getPassword() {
 16  return password;
 17 }

 18
 19 public void setPassword(String password) {
 20  this.password = password;
 21 }

 22
 23 public String getUser() {
 24  return user;
 25 }

 26
 27 public void setUser(String user) {
 28  this.user = user;
 29 }

 30
 31 public String getContent() {
 32  return content;
 33 }

 34
 35 public void setContent(String content) {
 36  this.content = content;
 37 }

 38
 39 public String getDatafrom() {
 40  return datafrom;
 41 }

 42
 43 public void setDatafrom(String datafrom) {
 44  this.datafrom = datafrom;
 45 }

 46
 47 public String getDatato() {
 48  return datato;
 49 }

 50
 51 public void setDatato(String datato) {
 52  this.datato = datato;
 53 }

 54
 55 public String getDate() {
 56  return date;
 57 }

 58
 59 public void setDate(String date) {
 60  this.date = date;
 61 }

 62
 63 public String getFrom() {
 64  return from;
 65 }

 66
 67 public void setFrom(String from) {
 68  this.from = from;
 69 }

 70
 71 public String getSubject() {
 72  return subject;
 73 }

 74
 75 public void setSubject(String subject) {
 76  this.subject = subject;
 77 }

 78
 79 public String getTo() {
 80  return to;
 81 }

 82
 83 public void setTo(String to) {
 84  this.to = to;
 85 }

 86
 87}

 88
 89
 90---------------------------------------------
 91
 92SMTPClient .java
 93
 94------------------------------
 95
 96//主要的功能就在這里面完成了
 97
 98package mail;
 99
100import java.io.BufferedReader;
101import java.io.BufferedWriter;
102import java.io.IOException;
103import java.io.InputStreamReader;
104import java.io.OutputStreamWriter;
105import java.net.Socket;
106import java.net.SocketException;
107import java.net.UnknownHostException;
108import java.util.StringTokenizer;
109
110import sun.misc.BASE64Encoder;
111
112public class SMTPClient {
113
114 private boolean debug=true;
115 BASE64Encoder encode=new BASE64Encoder();//用于加密后發送用戶名和密碼
116 public static void main(String[] args) throws UnknownHostException, IOException {
117  // TODO Auto-generated method stub
118  MailMessage message=new MailMessage();
119  message.setFrom("wasingmon@163.com");//發件人
120  message.setTo("wasingmon@eyou.com");//收件人
121  String server="smtp.163.com";//郵件服務器
122  message.setSubject("test");//郵件主題
123  message.setContent("test");//郵件內容
124  message.setDatafrom("wangxingmou@eyou.com");//發件人,在郵件的發件人欄目中顯示
125  message.setDatato("wasingmon@163.com");//收件人,在郵件的收件人欄目中顯示
126  message.setUser("wasingmon");//登陸郵箱的用戶名
127  message.setPassword("");//登陸郵箱的密碼
128  
129  SMTPClient smtp=new SMTPClient(server,25);
130  boolean flag;
131  flag=smtp.sendMail(message,server);
132  if(flag){
133   System.out.println("郵件發送成功!");
134  }

135  else{
136   System.out.println("郵件發送失敗!");
137  }

138
139 }

140 private Socket socket;
141 public SMTPClient(String server,int port) throws UnknownHostException, IOException{
142  try{
143   socket=new Socket(server,25);
144  }
catch(SocketException e){
145   System.out.println(e.getMessage());
146  }
catch(Exception e){
147   e.printStackTrace();
148  }
finally{
149   System.out.println("已經建立連接!");
150  }

151
152 }

153 //注冊到郵件服務器
154 public void helo(String server,BufferedReader in,BufferedWriter out) throws IOException{
155  int result;
156  result=getResult(in);
157  //連接上郵件服務后,服務器給出220應答
158  if(result!=220){
159   throw new IOException("連接服務器失敗");
160  }

161  result=sendServer("HELO "+server,in,out);
162  //HELO命令成功后返回250
163  if(result!=250)
164  {
165   throw new IOException("注冊郵件服務器失敗!");
166  }

167 }

168 
169 private int sendServer(String str,BufferedReader in,BufferedWriter out) throws IOException{
170  out.write(str);
171  out.newLine();
172  out.flush();
173  if(debug)
174  {
175   System.out.println("已發送命令:"+str);
176  }

177  return getResult(in);
178 }

179 public int getResult(BufferedReader in){
180  String line="";
181  try{
182   line=in.readLine();
183   if(debug){
184    System.out.println("服務器返回狀態:"+line);
185   }

186  }
catch(Exception e){
187   e.printStackTrace();
188  }

189  //從服務器返回消息中讀出狀態碼,將其轉換成整數返回
190  StringTokenizer st=new StringTokenizer(line," ");
191  return Integer.parseInt(st.nextToken());
192 }

193 
194 public void authLogin(MailMessage message,BufferedReader in,BufferedWriter out) throws IOException{
195  int result;
196  result=sendServer("AUTH LOGIN",in,out);
197  if(result!=334){
198   throw new IOException("用戶驗證失敗!");
199  }

200  
201   result=sendServer(encode.encode(message.getUser().getBytes()),in,out);
202   if(result!=334){
203   throw new IOException("用戶名錯誤!"); 
204   }

205   result=sendServer(encode.encode(message.getPassword().getBytes()),in,out);
206  
207   if(result!=235){
208    throw new IOException("驗證失敗!"); 
209  }

210 }

211 //開始發送消息,郵件源地址
212 public void mailfrom(String source,BufferedReader in,BufferedWriter out) throws IOException{
213  int result;
214  result=sendServer("MAIL FROM:<"+source+">",in,out);
215  if(result!=250){
216   throw new IOException("指定源地址錯誤");
217  }

218 }

219 // 設置郵件收件人
220 public void rcpt(String touchman,BufferedReader in,BufferedWriter out) throws IOException{
221  int result;
222  result=sendServer("RCPT TO:<"+touchman+">",in,out);
223  if(result!=250){
224   throw new IOException("指定目的地址錯誤!");
225  }

226 }

227 
228 //郵件體
229 public void data(String from,String to,String subject,String content,BufferedReader in,BufferedWriter out) throws IOException{
230  int result;
231  result=sendServer("DATA",in,out);
232  //輸入DATA回車后,若收到354應答后,繼續輸入郵件內容
233  if(result!=354){
234   throw new IOException("不能發送數據");
235  }

236  out.write("From: "+from);
237  out.newLine();
238  out.write("To: "+to);
239  out.newLine();
240  out.write("Subject: "+subject);
241  out.newLine();
242  out.newLine();
243  out.write(content);
244  out.newLine();
245  //句號加回車結束郵件內容輸入
246  result=sendServer(".",in,out);
247  System.out.println(result);
248  if(result!=250)
249  {
250   throw new IOException("發送數據錯誤");
251  }

252 }

253 
254 //退出
255 public void quit(BufferedReader in,BufferedWriter out) throws IOException{
256  int result;
257  result=sendServer("QUIT",in,out);
258  if(result!=221){
259   throw new IOException("未能正確退出");
260  }

261 }

262 
263 //發送郵件主程序
264 public boolean sendMail(MailMessage message,String server){
265  try{
266   BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
267   BufferedWriter out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
268   helo(server,in,out);//HELO命令
269   authLogin(message,in,out);//AUTH LOGIN命令
270   mailfrom(message.getFrom(),in,out);//MAIL FROM
271   rcpt(message.getTo(),in,out);//RCPT
272   data(message.getDatafrom(),message.getDatato(),message.getSubject(),message.getContent(),in,out);//DATA
273   quit(in,out);//QUIT
274  }
catch(Exception e){
275   e.printStackTrace();
276   return false;
277   
278  }

279  return true;
280 }

281
282}

283
方法二:用javaMail發送郵件
 1public class JavaMail {    
 2    //  發送郵件函數    
 3    public boolean sendMail(String mailTo, String mailSubject, String mailBody) {    
 4        //發送email    
 5        try {    
 6            //default account information    
 7            String smtpServer = "smtp.163.com";    
 8            String smtpAuth = "true";    
 9            String smtpUser = "xxxx";    
10            String smtpPassword = "xxxx";    
11            String From = "xxx@163.com";    
12            String To = mailTo;    
13            String Subject = mailSubject;    
14            String Text = mailBody;    
15            //        java.util.ResourceBundle resBundle;    
16            //        resBundle = java.util.ResourceBundle.getBundle("mailinfo",Locale.SIMPLIFIED_CHINESE);    
17            //        if (resBundle != null) {    
18            //          smtpServer = resBundle.getString("mail.smtp.host");    
19            //          smtpAuth = resBundle.getString("mail.smtp.auth");    
20            //          smtpUser = resBundle.getString("mail.smtp.user");    
21            //          smtpPassword = resBundle.getString("mail.smtp.password");    
22            //          From = resBundle.getString("mail.smtp.from");    
23            //        }    
24            Properties props = new Properties();    
25            Session sendMailSession;    
26            Transport transport;    
27            props.put("mail.smtp.host", smtpServer);    
28            props.put("mail.smtp.auth", smtpAuth);    
29            if ("true".equals(smtpAuth)) {    
30                //smtp服務器需要驗證,用MyAuthertiactor來創建mail session    
31                MyAuthenticator myauth = new MyAuthenticator(smtpUser,    
32                        smtpPassword);    
33                sendMailSession = Session.getInstance(props, myauth);    
34            }
 else {    
35                sendMailSession = Session.getInstance(props);    
36            }
    
37            //Debug    
38            sendMailSession.setDebug(true);    
39            Message newMessage = new MimeMessage(sendMailSession);    
40            newMessage.setFrom(new InternetAddress(From));    
41            newMessage.setRecipient(Message.RecipientType.TO,    
42                    new InternetAddress(mailTo));    
43            newMessage.setSubject(Subject);    
44            newMessage.setSentDate(new Date());    
45            newMessage.setText(Text);    
46            newMessage.saveChanges();    
47            transport = sendMailSession.getTransport("smtp");    
48            transport.send(newMessage, newMessage.getAllRecipients());    
49            transport.close();    
50        }
 catch (Exception mailEx) {    
51            System.err.println("Send Mail Error:" + mailEx.getMessage());    
52            return false;    
53        }
    
54        return true;    
55    }
    
56   
57    //smtp需要驗證時候的驗證類    
58    class MyAuthenticator extends javax.mail.Authenticator {    
59        private String strUser;    
60   
61        private String strPwd;    
62   
63        public MyAuthenticator(String user, String password) {    
64            this.strUser = user;    
65            this.strPwd = password;    
66        }
    
67   
68        protected PasswordAuthentication getPasswordAuthentication() {    
69            return new PasswordAuthentication(strUser, strPwd);    
70        }
    
71    }
    
72   
73}
   
74