java socket 实现SMTP协议 发送邮件

oscartang 贡献于2012-06-27

作者 微软用户  创建于2011-04-17 04:44:00   修改者微软用户  修改于2011-04-17 04:50:00字数6994

文档摘要:java socket 实现SMTP协议发送邮件
关键词:

java socket 实现SMTP协议 发送邮件 文章分类:Java编程 package com.socket.test; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.net.UnknownHostException; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; /** * 通过socket向smtp协议服务器发送邮件 * @author fuyanqing * */ public class SocketMail { String mailServer; String from; String to; String content; String lineFeet = "\r\n"; private int port = 25; Socket client; BufferedReader in; DataOutputStream os; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getMailServer() { return mailServer; } public void setMailServer(String mailServer) { this.mailServer = mailServer; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } /** * 初始化连接 * @return */ private boolean init(){ boolean boo = true; if(mailServer==null || "".equals(mailServer)){ return false; } try { client = new Socket(mailServer,port); in = new BufferedReader(new InputStreamReader(client.getInputStream())); os = new DataOutputStream(client.getOutputStream()); String isConnect = response(); if(isConnect.startsWith("220")){ }else{ System.out.println("建立连接失败:"+isConnect); boo = false; } } catch (UnknownHostException e) { System.out.println("建立连接失败!"); e.printStackTrace(); boo = false; } catch (IOException e) { System.out.println("读取流失败!"); e.printStackTrace(); boo = false; } return boo; } /** * 发送smtp指令 * 并返回服务器响应信息 */ private String sendCommand(String msg){ String result = null; try { os.writeBytes(msg); os.flush(); result = response(); } catch (IOException e) { e.printStackTrace(); } return result; } /** * 读取服务器端响应信息 * @return */ private String response(){ String result = null; try { result = in.readLine(); } catch (IOException e) { e.printStackTrace(); } return result; } /** * 关闭 */ private void close(){ try { os.close(); in.close(); client.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 发送邮件 * @return */ public boolean sendMail(){ //初始化 if(client==null){ if(init()){ }else{ return false; } } //判断from,to if(from==null || from.isEmpty() || to == null || to.isEmpty()){ return false; } //进行握手 String result = sendCommand("HELO "+mailServer+lineFeet); if(isStartWith(result,"250")){ }else{ System.out.println("握手失败:"+result); return false; } //验证发信人信息 String auth = sendCommand("AUTH LOGIN"+lineFeet); if(isStartWith(auth,"334")){ }else{ return false; } String user = sendCommand(new String(Base64.encode("*****".getBytes()))+lineFeet); if(isStartWith(user,"334")){ }else{ return false; } String pass = sendCommand(new String(Base64.encode("*****".getBytes()))+lineFeet); if(isStartWith(pass,"235")){ }else{ return false; } //发送指令 String f = sendCommand("Mail From:<"+from+">"+lineFeet); if(isStartWith(f,"250")){ }else{ return false; } String toStr = sendCommand("RCPT TO:<"+to+">"+lineFeet); if(isStartWith(toStr,"250")){ }else{ return false; } String data = sendCommand("DATA"+lineFeet); if(isStartWith(data,"354")){ }else{ return false; } StringBuilder sb = new StringBuilder(); sb.append("From:<"+from+">"+lineFeet); sb.append("To:<"+to+">"+lineFeet); sb.append("Subject:test"+lineFeet); sb.append("Date:2010/10/27 17:30"+lineFeet); sb.append("Content-Type:text/plain;charset=\"GB2312\""+lineFeet); sb.append(lineFeet); sb.append(content); sb.append(lineFeet+"."+lineFeet); String conStr = sendCommand(sb.toString()); if(isStartWith(conStr,"250")){ }else{ return false; } //quit String quit = sendCommand("QUIT"+lineFeet); if(isStartWith(quit,"221")){ }else{ return false; } close(); return true; } private boolean isStartWith(String res,String with){ return res.startsWith(with); } public static void main(String[] args){ SocketMail mail = new SocketMail(); mail.setMailServer("smtp.163.com"); mail.setFrom("*****@163.com"); mail.setTo("*****@163.com"); mail.setContent("hello,this is a test mail!"); boolean boo = mail.sendMail(); if(boo) System.out.println("邮件发送成功!"); else{ System.out.println("邮件发送失败!"); } } } ··························································································· SMTP的连接和收发过程: a.建立TCP连接。 b.客户端发送HELO命令以标识发件人自己的身份,然后客户端发送MAIL命令服务器端正希望以OK作为响应,表明准备接收。 c.客户端发送RCPT命令,以标识该电子邮件的计划接收人,可以有多个RCPT行 d.协商结束,发送邮件,用命令DATA发送 e.以.表示结束输入内容一起发送出去 f.结束此次发送,用QUIT命令退出。 SMTP的基本命令集: HELO   向服务器标识用户身份 MAIL   初始化邮件传输mail from: RCPT   标识单个的邮件接收人;常在MAIL命令后面可有多个rcpt to: DATA   在单个或多个RCPT命令后,表示所有的邮件接收人已标识,初始化数据传输,以.结束。 NOOP   无操作,服务器应响应OK RSET   重置会话,当前传输被取消 QUIT   结束会话 POP3简介: 在POP3协议中有三种状态,认可状态,处理状态,和更新状态。当客户机与服务器建立联系时,一旦客户机提供了自己身份并成功确认,即由认可状态转入处理状态,在完成相应的操作后客户机发出quit命令,则进入更新状态,更新之后最后重返认可状态。 POP3基本命令集: USER username PASS password    STAT  请求服务器发回关于邮箱的统计资料,如邮件总数和总字节数 LIST  返回邮件数量和每个邮件的大小 RETR [Msg#] 返回由参数标识的邮件的全部文本 DELE [Msg#] 服务器将由参数标识的邮件标记为删除,由quit命令执行 RSET 服务器将重置所有标记为删除的邮件,用于撤消DELE命令 NOOP 服务器返回一个肯定的响应 QUIT 更新 class POP3Demo {    private static Stri ng POP3Server = "pop.126.com";     private static String USERNAME = "username";//实际应用中改成真实的用户名     private static String PASSWORD = "password";//实际应用中改成真实的密码     public static void main(String[] args) {         int POP3Port = 110;         Socket client = null;         try {             // 向POP3服务程序建立一个套接字连接。             client = new Socket(POP3Demo.POP3Server, POP3Port);             // 创建一个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("user " + POP3Demo.USERNAME);             System.out.println("S:" + sockin.readLine());             sockout.println("pass " + POP3Demo.PASSWORD);             System.out.println("S:" + sockin.readLine());             sockout.println("stat");             String temp[] = sockin.readLine().split(" ");             int count = Integer.parseInt(temp[1]);//得到信箱中共有多少封邮件             for (int i = 1; i < count + 1; i++) {//依次打印出邮件的内容                 sockout.println("retr " + i);                 System.out.println("以下为第" + i + "封邮件的内容");                 while (true) {                     String reply = sockin.readLine();                     System.out.println(reply);                     if (reply.toLowerCase().equals(".")) {                         break;                     }                 }             }           } 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) {}         }     } }

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 5 金币 [ 分享文档获得金币 ] 2 人已下载

下载文档