import java.io.*;
import java.net.*;
/**
* <p>Title: SMTP協議內送郵件</p>
* <p>Description: 通過Socket串連POP3伺服器,使用SMTP協議內送郵件伺服器中的郵件</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: </p>
* @version 1.0
*/
class POP3Demo
{
/**
*<br>方法說明:主方法,接收使用者輸入
*<br>輸入參數:
*<br>傳回型別:
*/
public static void main(String[] args){
if(args.length!=3){
System.out.println("USE: java POP3Demo mailhost user password");
}
new POP3Demo().receive(args[0],args[1],args[2]);
}
/**
*<br>方法說明:內送郵件
*<br>輸入參數:String popServer 伺服器位址
*<br>輸入參數:String popUser 信箱使用者名
*<br>輸入參數:String popPassword 郵箱密碼
*<br>傳回型別:
*/
public static void receive (String popServer, String popUser, String popPassword)
{
String POP3Server = popServer;
int POP3Port = 110;
Socket client = null;
try
{
// 建立一個串連到POP3服務程式的通訊端。
client = new Socket (POP3Server, POP3Port);
//建立一個BufferedReader對象,以便從通訊端讀取輸出。
InputStream is = client.getInputStream ();
BufferedReader sockin;
sockin = new BufferedReader (new InputStreamReader (is));
//建立一個PrintWriter對象,以便向通訊端寫入內容。
OutputStream os = client.getOutputStream ();
PrintWriter sockout;
sockout = new PrintWriter (os, true); // true for auto-flush
// 顯示POP3握手資訊。
System.out.println ("S:" + sockin.readLine ());
/*-- 與POP3伺服器握手過程 --*/
System.out.print ("C:");
String cmd = "user "+popUser;
// 將使用者名稱發送到POP3服務程式。
System.out.println (cmd);
sockout.println (cmd);
// 讀取POP3服務程式的回應訊息。
String reply = sockin.readLine ();
System.out.println ("S:" + reply);
System.out.print ("C:");
cmd = "pass ";
// 將密碼發送到POP3服務程式。
System.out.println(cmd+"*********");
sockout.println (cmd+popPassword);
// 讀取POP3服務程式的回應訊息。
reply = sockin.readLine ();
System.out.println ("S:" + reply);
System.out.print ("C:");
cmd = "stat";
// 擷取郵件資料。
System.out.println(cmd);
sockout.println (cmd);
// 讀取POP3服務程式的回應訊息。
reply = sockin.readLine ();
System.out.println ("S:" + reply);
if(reply==null) return;
System.out.print ("C:");
cmd = "retr 1";
// 將接收第一豐郵件命令發送到POP3服務程式。
System.out.println(cmd);
sockout.println (cmd);
// 輸入了RETR命令並且返回了成功的回應碼,持續從通訊端讀取輸出,
// 直到遇到<CRLF>.<CRLF>。這時從通訊端讀出的輸出就是郵件的內容。
if (cmd.toLowerCase ().startsWith ("retr") &&
reply.charAt (0) == ´+´)
do
{
reply = sockin.readLine ();
System.out.println ("S:" + reply);
if (reply != null && reply.length () > 0)
if (reply.charAt (0) == ´.´)
break;
}
while (true);
cmd = "quit";
// 將命令發送到POP3服務程式。
System.out.print (cmd);
sockout.println (cmd);
}
catch (IOException e)
{
System.out.println (e.toString ());
}
finally
{
try
{ if (client != null)
client.close ();
}
catch (IOException e)
{
}
}
}
}