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. C#嵌套类型

    1.什么是嵌套类型:在类和结构内部定义的类型称为嵌套类型,例如 class Container { class Nested { Nested() { } } } 2.不管外部类型是结构还是类.嵌套类 ...

  2. 01顺序栈_Stack---(栈与队列)

    #include "stdio.h" #include "stdlib.h" #include "io.h" #include " ...

  3. 用 CSS 隐藏页面元素的 5 种方法

    原文链接:用 CSS 隐藏页面元素的 5 种方法,转载请注明来源! 用 CSS 隐藏页面元素有许多种方法.你可以将 opacity 设为 0.将 visibility 设为 hidden.将 disp ...

  4. checkbox prop()函数

    1.设置checkbox选中状态 ①选中: .prop('checked',true); ②不选中:.prop('checked',false); 2.获取checkbox选中状态 .prop('ch ...

  5. 关于MessageBox的用法

    今天编写MFC工程的时候,使用MessageBox函数,老是出错,不断从网上查找解决方案,最后找到了 MessageBox( _T("Help, Something went wrong.& ...

  6. make menuconfig出错需要安装文件

    $ make menuconfig *** Unable to find the ncurses libraries or the *** required header files. *** 'ma ...

  7. ehcache集群的配置

    一:配置环境 本文是在测试demo的基础上写的,服务器包括申请的两台服务器和本机,共三台服务器.demo的目标是实现三台服务器之间共享cache. 申请的两台服务器地址分别是172.19.100.15 ...

  8. jQuery(function(){})与(function(){})(jQuery)的区别

    jQuery(function(){ });/$(function(){ });全写为 $(document).ready(function(){}); 意义为在DOM加载完毕后执行了ready()方 ...

  9. PHP 5.6.6 上运行 ecshop 2.7.3 不兼容问题整合

    在安装完php在自己的服务器上以后, 发现在静态网页上出现了很多 error. 在网上查找过后发现,大部分问题是因为 PHP发展到PHP5.5版本以后,有了很多细微的变化.而ECSHOP官方更新又太慢 ...

  10. linux磁盘设备知识

    linux分区数字编号: 1.分区数字编号1至4留给主分区或扩展分区使用,逻辑分区编号从5开始. 2.IDE硬盘设备名均以/dev/hd开头,不同硬盘编号依次是/dev/hda/./dev/hdb./ ...