Java SMTP 发送邮件

// 这是欠安鸣哥一年多的代码。一年零三个月以前就应该实现的。结果拖到今天,还费了一下午。

package javaMailTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class MailSender {
	private String smtpServer = "smtp.yeah.net";
	private int port = 25;
	
	public static void main(String[] args) {
		Message msg = new Message(
				"ourauc@yeah.net",		// Sender
				"wzhi1997@qq.com",
				"成功",
				"已出,请及时检查更新");
		new MailSender().sendMail(msg);
	}
	public void sendMail(Message msg) {
		Socket socket = null;
		try{
			socket = new Socket(smtpServer, port);
			BufferedReader br = getReader(socket);
			PrintWriter pw = getWriter(socket);
			String localhost = InetAddress.getLocalHost().getHostName();
			
			String username = msg.from;
			String password = "12345@#$%^";
			username = new sun.misc.BASE64Encoder().encode(username.getBytes());
			password = new sun.misc.BASE64Encoder().encode(password.getBytes());
			
			sendAndReceive(null, br, pw);
			sendAndReceive("EHLO " + localhost, br, pw);
			sendAndReceive("AUTH LOGIN", br, pw);
			sendAndReceive(username, br, pw);
			sendAndReceive(password, br, pw);
			sendAndReceive("MAIL FROM:<" + msg.from + ">", br, pw);
			sendAndReceive("RCPT TO:<" + msg.to + ">", br, pw);
			sendAndReceive("DATA", br, pw);
			sendAndReceive(msg.data, br, pw);
			sendAndReceive(".", br, pw);
			sendAndReceive("QUIT", br, pw);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e2) {
				e2.printStackTrace();
			}
		}
	}
	
	private void sendAndReceive(String str, BufferedReader br, PrintWriter pw) throws IOException {
		if (str != null) {
			System.out.println("Client>" + str);
			pw.println(str);
		}
		String response = "";
		
		if ((response = br.readLine()) != null) {
			System.out.println("Server>" + response);
		}
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private PrintWriter getWriter(Socket socket) throws IOException {
		OutputStream socketOut = socket.getOutputStream();
		return new PrintWriter(socketOut,true);
	}
	
	private BufferedReader getReader(Socket socket) throws IOException {
		InputStream socketIn = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(socketIn));
	}
}

class Message {
	String from;
	String to;
	String subject;
	String content;
	String data;
	public Message(String from, String to, String subject, String content) {
		this.from = from;
		this.to = to;
		this.subject = subject;
		this.content = content;
		data = "From:ourauc@yeah.net\r\nTo:wzhi1997@qq.com\r\nSubject:" + subject + "\r\n\r\n" + content;
	}
}

// 最后还是致敬安鸣哥!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据