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;

/**
 * @author zhaohongbing
 *
 */
@SuppressWarnings("unused")
public class SockerMail {
    String mailServer;
    String from;
    String to;
    String subject;
    String content;
    String lineFeet = "\r\n";
    private int port = 25;
    
    Socket client;
    BufferedReader bf;
    DataOutputStream dos;
    
    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;
    }

public String getSubject(){
        return subject;
    }

public void setSubject(String sub){
        this.subject = sub;
    }
    
    /**
     * 初始化连接
     * @return
     */
    private boolean init(){
        System.out.println("init be invoke");
        boolean boo = true;
        if(mailServer == null || "".equals(mailServer)){
            return false;
        }
        try{
            client = new Socket(mailServer, port);
            bf = new BufferedReader(new InputStreamReader(client.getInputStream()));
            dos = new DataOutputStream(client.getOutputStream());
            String isConnect = getResponse();
            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;
        }
        System.out.println("init result = " +boo);
        return boo;
    }
    
    /**
     * 发送smtp指令
     * 并返回服务器响应信息
     * @param msg
     * @return
     */
    private String sendCommand(String msg){
        String result = null;
        try{
            dos.writeBytes(msg);
            dos.flush();
            result = getResponse();
        }catch(IOException e){
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 读取服务器端响应信息
     * @return
     */
    private String getResponse(){
        String result = null;
        try{
            result = bf.readLine();
        }catch(IOException e){
            e.printStackTrace();
        }
        return result;
    }
    
    
    /**
     * 关闭
     */
    private void close(){
        try{
            dos.close();
            bf.close();
            client.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    
    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")){
            System.out.println("握手结果:"+true);
        }else{
            System.out.println("握手失败:"+result);
            return false;
        }
        //验证发信人信息
//        String auth = sendCommand("AUTH LOGIN"+lineFeet);
//        if(isStartWith(auth,"334")){
//            System.out.println("验证发信人信息结果:"+true);
//        }else{
//            return false;
//        }
//        String user = sendCommand(new String(Base64.encode("anszhao@163.com".getBytes()))+lineFeet);
//        System.out.println("user = " +user);
//        if(isStartWith(user, "334")){
//            System.out.println("验证user信息结果:"+true);
//        }else{
//            return false;
//        }
//        String pass = sendCommand(new String(Base64.encode("".getBytes()))+lineFeet);
//        System.out.println("pass = " +pass);
//        if(isStartWith(pass, "235")){
//            System.out.println("验证pass信息结果:"+true);
//        }else{
//            System.out.println("验证pass信息结果:"+false);
//            return false;
//        }
        
        //发送指令
        String f = sendCommand("Mail From:<"+from+">"+lineFeet);
        System.out.println("发送指令结果:"+f);
        if(isStartWith(f,"250")){
            System.out.println("发送指令结果:"+true);
        }else{
            System.out.println("发送指令结果:"+false);
            return false;
        }
        String toStr = sendCommand("RCPT TO:<"+to+">"+lineFeet);
        System.out.println("验证toStr结果:"+toStr);
        if(isStartWith(toStr,"250")){
            System.out.println("验证toStr结果:"+true);
        }else{
            return false;
        }
        
        String data = sendCommand("DATA"+lineFeet);
        if(isStartWith(data,"354")){
            System.out.println("验证data信息结果:"+true);
        }else{   
            return false;
        }
        
        StringBuilder sb = new StringBuilder();
        sb.append("From:<"+from+">"+lineFeet);
        sb.append("To:<"+to+">"+lineFeet);
        sb.append("Subject:" +subject+lineFeet);
        sb.append("Date:2014/06/27 17:30"+lineFeet);
        sb.append("Content-Type:text/plain;charset=\"GB2312\",\"UTF-8\""+lineFeet);
        sb.append(lineFeet);
        sb.append(content);
        sb.append(lineFeet+"."+lineFeet);
        
        String conStr = sendCommand(sb.toString());
        if(isStartWith(conStr,"250")){
            System.out.println("验证conStr信息结果:"+true);
        }else{
            return false;
        }
        
        //quit 
        String quit = sendCommand("QUIT"+lineFeet);
        if(isStartWith(quit,"221")){
            System.out.println("验证quit信息结果:"+true);
        }else{
            return false;
        }
        close();
        return true;
    }
    
    /**
     *
     * 检查字符串开头
     */
    private boolean isStartWith(String res, String with){
        return res.startsWith(with);
    }

/**
     * @param args
     */
    public static void main(String[] args) {
        SockerMail mail = new SockerMail();
        mail.setMailServer("stmp.mail.163.com");
        mail.setFrom("anson@163.com");
        mail.setTo("anson@163.com");
        mail.setSubject("[Test Email]");
        mail.setContent("Hello,this is a test mail, please replay me if you have receviced it");
        boolean boo = mail.sendMail();
        if(boo){
            System.out.println("邮件发送成功");
        }else{
            System.out.println("邮件发送失败");
        }

}

}

Java通过socket实现smtp协议发送邮件的更多相关文章

  1. 使用java mail的网易smtp协议 发送邮件

    package com.enation.newtest; import java.security.GeneralSecurityException; import java.util.Propert ...

  2. PHP用socket连接SMTP服务器发送邮件

    PHP用socket连接SMTP服务器发送邮件 PHP用socket连接SMTP服务器发送邮件学习实验记录: 分析与SMTP会话的一般流程 1. HELO XXX \r\n //XXX就是自己起个名字 ...

  3. SMTP 协议发送邮件的整体过程

    使用 SMTP 发送邮件_使用 SMTP 发送邮件_发送邮件_用户指南_邮件推送-阿里云 https://help.aliyun.com/knowledge_detail/51622.html 通过 ...

  4. java实现发送邮件服务器,SMTP协议发送邮件

    1.采用SMTP的邮件发送协议.准备:在网易注册一个邮箱,进入设置开启SMTP/pop3协议 2.接下来就是java代码实现了,下面都有注释,就不多做解释了. public class mail { ...

  5. 通过telnet使用smtp协议发送邮件

    smtp协议是一个简单的邮件传输协议,利用它我们可以将邮件发送给别人,这里将通过telnet这个程序利用smtp协议从网易向gmail发送一封邮件 网上不少有说使用telnet发送邮件的文章,我也看过 ...

  6. 使用SMTP协议发送邮件

    class Program { static void Main(string[] args) { ) { try { inputmodel obj = new inputmodel(args); S ...

  7. C语言利用SMTP协议发送邮件

    #ifdef WIN32 #include <windows.h> #include <stdio.h> #else #include <stdio.h> #inc ...

  8. Java的socket服务UDP协议

    练习1 接收类 package com.socket.demo; import java.io.IOException; import java.net.DatagramPacket; import ...

  9. QTP使用Smtp协议发送邮件

    NameSpace = "http://schemas.microsoft.com/cdo/configuration/" Set Email = CreateObject(&qu ...

随机推荐

  1. 关于Ionic的安装

    Ionic是一个前端的框架,帮助开发者使用HTML5, CSS3和JavaScript做出原生应用. http://ionicframework.com/getting-started/ 这里介绍了如 ...

  2. sharepoint 2013 suitbar

    参考链接:http://academy.bindtuning.com/customize-sharepoint-2013-and-office-365-suite-bar/

  3. 关于不使用web服务实现文本框自动完成扩展

    来博客园很久了,一直是伸手党,呵呵,现在终于申请了一个账号并开通了博客 下面分享下之前在一个项目里遇到的问题 前段时间在一个项目里要求在文本框内输入要搜索的内容,自动提示与此内容相关的词条 当时在博客 ...

  4. Oracle 自连接 / 外连接 / 子查询

    --连接查询的三种格式 select ename, deptno,dname from emp natural join dept; select ename, deptno,dname from e ...

  5. JSON字符串转换为JSON对象

    一.JSON字符串转换为JSON对象 A:eval函数 eval函数可以直接将本质符合或者近似符合JSON格式的字符串转换为JSON对象,使用方式如: eval('(' + str + ')'); / ...

  6. bootstrap table 行号 显示行号 添加行号 bootstrap-table 行号

    思想:借助bootstrap-table 本身的index属性, 巧妙的的通过formatter 实现 { field: 'Number', title: 'Number', formatter: f ...

  7. svg学习笔记(一)

    SVG——可扩展适量图形,基于XML PC端:IE9+   wap端:表现良好,适合使用 基础图形: line(线段)  <line x1="25" y1="150 ...

  8. LAMP虚拟主机配置以及控制目录访问

    3.基于域名的虚拟主机配置 NameVirtualHost192.168.3.32:80#apache2.2.xx版本需要开启此选项,而且要和下面的保持一致:2.4.x版本就不需要此项设置了 < ...

  9. python--multiprocessing多进程总结

    由于GIL的存在,python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程.Python提供了非常好用的多进程包multiproces ...

  10. 利用数据库链做DML操作时报ORA-02069: global_names parameter must be set to TRUE for this operation

    按照 http://space.itpub.net/195110/viewspace-711110 的说法顺利解决问题. 通过DBLink更新远程数据的时候,如果使用到本地的sequence.函数.过 ...