www.pudn.com > JMail4Email.rar > SocketMail.java


import java.io.BufferedReader; 
import java.io.PrintWriter; 
import java.io.IOException; 
import java.net.Socket; 
 
public class SocketMail { 
 
	public static void send(String smtpHost, String sender, String recipients, 
					  String subject, String msg) { 
 
		Socket mailSocket; 
		BufferedReader is; 
		PrintWriter outToServer; 
 
		try { 
			// Step 1:  Connect to SMTP server 
			System.out.println("opening connection to server: " + smtpHost); 
			mailSocket = new Socket(smtpHost, 25); 
			System.out.println("connected"); 
 
			// Step 2:  Get an output stream for the socket connection 
			outToServer= new PrintWriter (mailSocket.getOutputStream()); 
 
			// Step 3:  Compose the message using the SMTP commands 
			System.out.println("composing message"); 
			outToServer.println("MAIL FROM: <" + sender + ">"); 
			outToServer.println("RCPT TO: <" + recipients + ">"); 
			outToServer.println("DATA"); 
			outToServer.println("SUBJECT: " + subject); 
			outToServer.println("X-Mailer: SocketMail"); 
			outToServer.println(msg); 
			outToServer.println(".\n"); 
 
			outToServer.flush(); 
			mailSocket.close(); 
			System.out.println("message sent"); 
		} 
		catch (IOException exc) 
		{ 
			System.out.println(exc); 
		} 
	} 
 
	public static void main(String[] args) { 
		if (args.length != 3) { 
			System.out.println("Usage:  java SocketMail   "); 
			System.exit(1); 
		} 
 
		String smtpHost = args[0]; 
		String from = args[1]; 
		String to = args[2]; 
		String subject = "Test Message"; 
		StringBuffer theMessage = new StringBuffer(); 
		theMessage.append("Hello,\n\n"); 
		theMessage.append("Hope all is well.\n"); 
		theMessage.append("Cheers!"); 
 
		SocketMail.send(smtpHost, from, to, subject, theMessage.toString()); 
	} 
}