import java.net.*;
import java.io.*;
/**
* <p>Title: 使用SMTP發送郵件</p>
* <p>Description: 本實例通過使用socket方式,根據SMTP協議發送郵件</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: sendSMTPMail.java</p>
* @version 1.0
*/
public class sendSMTPMail {
/**
*<br>方法說明:主方法
*<br>輸入參數:1。服務器ip;2。對方郵件地址
*<br>返回類型:
*/
public static void main(String[] arges) {
if(arges.length!=2){
System.out.println("use java sendSMTPMail hostname | mail to");
return;
}
sendSMTPMail t = new sendSMTPMail();
t.sendMail(arges[0], arges[1]);
}
/**
*<br>方法說明:發送郵件
*<br>輸入參數:String mailServer 郵件接收服務器
*<br>輸入參數:String recipient 接收郵件的地址
*<br>返回類型:
*/
public void sendMail(String mailServer, String recipient) {
try {
//有Socket打開25端口
Socket s = new Socket(mailServer, 25);
//緩存輸入和輸出
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream(), "8859_1"));
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(s.getOutputStream(), "8859_1"));
//發出“HELO”命令,表示對服務器的問候
send(in, out, "HELO theWorld");
//告訴服務器我的郵件地址,有些服務器要校驗這個地址
send(in, out, "MAIL FROM: <>");
//使用“RCPT TO”命令告訴服務器解釋郵件的郵件地址
send(in, out, "RCPT TO: " + recipient);
//發送一個“DATA”表示下面將是郵件主體
send(in, out, "DATA");
//使用Subject命令標注郵件主題
send(out, "Subject: 這是一個測試程序!");
//使用“From”標注郵件的來源
send(out, "From: riverwind <>");
send (out, "\n");
//郵件主體
send(out, "這是一個使用SMTP協議發送的郵件!如果打擾請刪除!");
send(out, "\n.\n");
//發送“QUIT”端口郵件的通訊
send(in, out, "QUIT");
s.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
*<br>方法說明:發送信息,並接收回信
*<br>輸入參數:
*<br>返回類型:
*/
public void send(BufferedReader in, BufferedWriter out, String s) {
try {
out.write(s + "\n");
out.flush();
System.out.println(s);
s = in.readLine();
System.out.println(s);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
*<br>方法說明:重載方法。向socket寫入信息
*<br>輸入參數:BufferedWriter out 輸出緩沖器
*<br>輸入參數:String s 寫入的信息
*<br>返回類型:
*/
public void send(BufferedWriter out, String s) {
try {
out.write(s + "\n");
out.flush();
System.out.println(s);
}
catch (Exception e) {
e.printStackTrace();
}
}
}