} catch (IOException e) {
System.out.println(e.toString());
} finally {
try {
if (client != null) {
client.close();
}
} catch (IOException e) {}
}
}
}
class SMTPDemo {
//以下三项请在使用时改成真实的信箱地址
//并且注意,SMTPServer和receiver必须是同一个服务器
private static String sender = "sender";
private static String receiver = "receiver";
private static String SMTPServer = "smtpserver";
public static void main(String[] args) {
int SMTPPort = 25;
Socket client = null;
try {
// 向SMTP服务程序建立一个套接字连接。
client = new Socket(SMTPDemo.SMTPServer, SMTPPort);
// 创建一个BufferedReader对象,以便从套接字读取输出。
InputStream is = client.getInputStream();
BufferedReader sockin = new BufferedReader(new InputStreamReader(is));
// 创建一个PrintWriter对象,以便向套接字写入内容。
OutputStream os = client.getOutputStream();
PrintWriter sockout = new PrintWriter(os, true);
// 显示同SMTP服务程序的握手过程。
System.out.println("S:" + sockin.readLine());
sockout.println("helo");
System.out.println("S:" + sockin.readLine());
sockout.println("mail from: " + "<" + SMTPDemo.sender + ">");
System.out.println("S:" + sockin.readLine());
sockout.println("rcpt to: " + "<" + SMTPDemo.receiver + ">");
System.out.println("S:" + sockin.readLine());
sockout.println("data");
//发送邮件标题
sockout.println("subject: 你好");
//发送邮件内容
sockout.println("ni hao");
sockout.println("wo shi li jian");
//此处的.为特殊标记,表示邮件结束
sockout.println(".");
sockout.println("rset");
sockout.println("quit");
} catch (IOException e) {
System.out.println(e.toString());
} finally {
try {
if (client != null) {
client.close();
}
} catch (IOException e) {}
}
}
}