`
stephen830
  • 浏览: 2969316 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

晒下以前根据RFC821SMTP协议写的发Email方法

    博客分类:
  • java
阅读更多
★★★ 本篇为原创,需要引用转载的朋友请注明:《 http://stephen830.iteye.com/blog/255099 》 谢谢支持! ★★★

这是老早以前根据RFC821协议[SIMPLE MAIL TRANSFER PROTOCOL]写的用于发email的方法。附件部分有点问题。有兴趣的朋友可以参考下。

关于RFC821协议[SIMPLE MAIL TRANSFER PROTOCOL]的具体内容可以访问: http://james.apache.org/server/rfclist/smtp/rfc0821.txt

下面是MailTool.java的具体内容:

/*
 * Created on 2005-6-1
 * Author stephen
 * Email zhoujianqiang AT gmail DOT com
 * CopyRight(C)2005-2008 , All rights reserved.
 */
package com.soft4j.utility;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 电子邮件Email的处理类.
 * 
 * @author stephen
 * @version 1.0.0
 */
public final class MailTool {

    private final static String END_FLAG = "\r\n";//SMTP/ESMTP命令结束标记
    private final static String EMAIL_ATTACH_SIGN = "=====att";//邮件附件的表示符号

    private String smtpServer = null;//邮件发送服务器域名
    private int smtpPort = 25;//邮件发送端口
    private Socket clientMailSocket;//邮件连接socket
    private InputStream inData;//接收数据    
    private OutputStream outData;//发送数据
    private String mailUserName = null;//邮件账户
    private String mailUserPass = null;//邮件账户的密码
    private String mailTo = null;//邮件发送目标
    private String mailFrom = null;//邮件发送人
    private String mailSubject = null;//邮件主题
    private String mailBody = null;//邮件正文   
    private String mailShowTo = null;//邮件内容抬头部分-邮件发送目标
    private String mailShowFrom = null;//邮件内容抬头部分-邮件发送人
    private String[] mailAttachFile = null;//邮件附件对应的本地文件名(包含绝对路径)
    private int mailType = 1;//邮件类型:1=文本邮件,2=HTML邮件
    
    /**
     * @return Returns the mailAttachFile.
     */
    public String[] getMailAttachFile() {
        return mailAttachFile;
    }
    /**
     * @param mailAttachFile The mailAttachFile to set.
     */
    public void setMailAttachFile(String[] mailAttachFile) {
        this.mailAttachFile = mailAttachFile;
    }
    /**
     * @return Returns the mailShowFrom.
     */
    public String getMailShowFrom() {
        return mailShowFrom;
    }
    /**
     * @param mailShowFrom The mailShowFrom to set.
     */
    public void setMailShowFrom(String mailShowFrom) {
        this.mailShowFrom = mailShowFrom;
    }
    /**
     * @return Returns the mailShowTo.
     */
    public String getMailShowTo() {
        return mailShowTo;
    }
    /**
     * @param mailShowTo The mailShowTo to set.
     */
    public void setMailShowTo(String mailShowTo) {
        this.mailShowTo = mailShowTo;
    }

    
    /**
     * @return Returns the mailBody.
     */
    public String getMailBody() {
        return mailBody;
    }
    /**
     * @param mailBody The mailBody to set.
     */
    public void setMailBody(String mailBody) {
        this.mailBody = mailBody;
    }
    /**
     * @return Returns the mailFrom.
     */
    public String getMailFrom() {
        return mailFrom;
    }
    /**
     * @param mailFrom The mailFrom to set.
     */
    public void setMailFrom(String mailFrom) {
        this.mailFrom = mailFrom;
    }
    /**
     * @return Returns the mailSubject.
     */
    public String getMailSubject() {
        return mailSubject;
    }
    /**
     * @param mailSubject The mailSubject to set.
     */
    public void setMailSubject(String mailSubject) {
        this.mailSubject = mailSubject;
    }
    /**
     * @return Returns the mailTo.
     */
    public String getMailTo() {
        return mailTo;
    }
    /**
     * @param mailTo The mailTo to set.
     */
    public void setMailTo(String mailTo) {
        this.mailTo = mailTo;
    }
    /**
     * @return Returns the mailUserName.
     */
    public String getMailUserName() {
        return mailUserName;
    }
    /**
     * @param mailUserName The mailUserName to set.
     */
    public void setMailUserName(String mailUserName) {
        this.mailUserName = mailUserName;
    }
    /**
     * @return Returns the mailUserPass.
     */
    public String getMailUserPass() {
        return mailUserPass;
    }
    /**
     * @param mailUserPass The mailUserPass to set.
     */
    public void setMailUserPass(String mailUserPass) {
        this.mailUserPass = mailUserPass;
    }
    
    

    /**
     * 获取属性-
     * @return Returns the mailType.
     */
    public int getMailType() {
        return mailType;
    }
    /**
     * 设置属性-
     * @param mailType The mailType to set.
     */
    public void setMailType(int mailType) {
        this.mailType = mailType;
    }
    /**
     * 构造器方法.
     * @param _smtpServer smtp服务器名(ip地址)
     * @param _smtpPort smtp端口号.
     */
    public MailTool(String smtpServer,int smtpPort){
        this.smtpServer = smtpServer;
        this.smtpPort = smtpPort;
    }
    
    
    /**
     * 与smtp邮件服务器建立连结.
     * @return
     */
    public boolean createConnection(){
        try {
            freeAll();
            clientMailSocket = new Socket(smtpServer, smtpPort);
            inData = clientMailSocket.getInputStream();
            outData = clientMailSocket.getOutputStream();
            fetchCMDResult();//当首次连接服务器后有返回值,必须取走该返回值,否则后面命令的返回值无法判断
        } catch (IOException e) {
            System.out.println("Can't create the connection with " + smtpServer + "on port " + smtpPort + ".", Log.STD_ERR);
            return false;
        }
        return true;
    }
    
    /**
     * 
     * @param in
     * @return
     */
    public static String response(InputStream in){
        byte[] buffer = new byte[1024];
        StringBuffer inData = new StringBuffer();
        int n = 0;
        try {
                n = in.read(buffer);
                inData.append(new String(buffer, 0, n));
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inData.toString();

    }
    
    public static void send(String s, OutputStream out){
        byte[] buffer = s.getBytes();
        try {
            out.write(buffer);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public String fetchCMDResult(){
        return response(inData);
    }
    
    public boolean sendCmd(String _cmd) {
        if (_cmd != null) {
            send(_cmd,outData);
        }
        return true;
    }
    
    /**
     * 发送邮件
     * 服务器为ESMTP时候采用本方法
     * @return true=send ok,false=send failed.
     */
    public boolean sendMail() {
        
        //打开与邮件服务器的连接
        if(!createConnection()){
            return false;
        }
        StringBuffer theContent = new StringBuffer();

        //EHLO
        theContent.append("EHLO ");
        theContent.append(smtpServer);
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        if(fetchCMDResult().indexOf("250")==-1) return false;
        //AUTH LOGIN
        theContent.delete(0,theContent.length());
        theContent.append("AUTH LOGIN");
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        try { Thread.sleep(5000); } catch (Exception e) {}
        if(fetchCMDResult().indexOf("334")==-1) return false;
        //用户名
        theContent.delete(0,theContent.length());
        theContent.append(Base64Encode(this.mailUserName));
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        if(fetchCMDResult().indexOf("334")==-1) return false;
        //密码
        theContent.delete(0,theContent.length());
        theContent.append(Base64Encode(this.mailUserPass));
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        try { Thread.sleep(5000); } catch (Exception e) {}
        if(fetchCMDResult().indexOf("235")==-1) return false;
        //邮件发送者
        theContent.delete(0,theContent.length());
        theContent.append("MAIL FROM:");
        theContent.append("<");
        theContent.append(this.mailFrom);
        theContent.append(">");
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        if(fetchCMDResult().indexOf("250")==-1) return false;
        //邮件发送目标地址
        theContent.delete(0,theContent.length());
        theContent.append("RCPT TO:");
        theContent.append("<");
        theContent.append(this.mailTo);
        theContent.append(">");
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        if(fetchCMDResult().indexOf("250")==-1) return false;
        
        //邮件内容-开始
        theContent.delete(0,theContent.length());
        theContent.append("DATA");
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        if(fetchCMDResult().indexOf("354")==-1) return false;
        //邮件内容-邮件抬头部分
        theContent.delete(0,theContent.length());
        theContent.append("From:");
        theContent.append(this.mailShowFrom);
        theContent.append(END_FLAG);
        theContent.append("To:");
        theContent.append(this.mailShowTo);
        theContent.append(END_FLAG);
        theContent.append("Subject:");
        theContent.append(this.mailSubject);
        theContent.append(END_FLAG);
        theContent.append("Mime-Version: 1.0");
        theContent.append(END_FLAG);
        

        theContent.append("Content-Type: multipart/mixed;Boundary=\"");//设置附件表示符
        theContent.append(EMAIL_ATTACH_SIGN);
        theContent.append("\"");
        theContent.append(END_FLAG);//在正文内容前必须有2个END_FLAG标记
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());

        //邮件内容-正文部分
        theContent.delete(0,theContent.length());
        theContent.append("--");
        theContent.append(EMAIL_ATTACH_SIGN);
        theContent.append(END_FLAG);
        switch(mailType){
            case 2:theContent.append("Content-type:text/html;");break;
            default:theContent.append("Content-type:text/plain;");break;
        }
        theContent.append(END_FLAG);
        theContent.append("Content-Transfer-Encoding: base64");
        theContent.append(END_FLAG);
        theContent.append(END_FLAG);
        theContent.append(Base64Encode(this.mailBody));
        theContent.append(END_FLAG);
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        
        //邮件内容-附件部分
        mailAttachFile = null;
        if(mailAttachFile!=null && mailAttachFile.length>0){
            for(int i=0;i<this.mailAttachFile.length;i++){
                //发送附件抬头
                theContent.delete(0,theContent.length());
                theContent.append("--");
                theContent.append(EMAIL_ATTACH_SIGN);
                theContent.append(i);
                theContent.append(END_FLAG);
                theContent.append("Content-Type:image/gif;name=\"aaa.gif\"");
                theContent.append(END_FLAG);
                theContent.append("Content-Transfer-Encoding:base64");
                theContent.append(END_FLAG);
                theContent.append("Content-Disposition:attachment;name=\"aaa.gif\"");
                theContent.append(END_FLAG);
                theContent.append(END_FLAG);
                sendCmd(theContent.toString());
                
                //发送附件内容
                sendBase64Data(new StringBuffer(Base64Encode(readFile(mailAttachFile[i]))));
                
                //发送附件结束
                /*
                theContent = new StringBuffer();
                theContent.append(END_FLAG);
                theContent.append("--");
                theContent.append(EMAIL_ATTACH_SIGN);
                theContent.append(i);
                theContent.append("--");
                theContent.append(END_FLAG);
                sendCmd(theContent.toString());
                */
            }
            
        }
        
        
        //发送附件结束
        theContent.delete(0,theContent.length());
        theContent.append(END_FLAG);
        theContent.append(END_FLAG);
        theContent.append("--");
        theContent.append(EMAIL_ATTACH_SIGN);
        theContent.append("--");
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        
        //邮件内容-结束标记
        theContent.delete(0,theContent.length());
        theContent.append(END_FLAG);
        theContent.append(".");
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        if(fetchCMDResult().indexOf("250")==-1) return false;
        
        //退出断开服务器连接
        theContent.delete(0,theContent.length());
        theContent.append("QUIT");
        theContent.append(END_FLAG);
        sendCmd(theContent.toString());
        fetchCMDResult();
        
        //邮件发送成功后释放资源
        freeAll();
        theContent = null;
        
        return true;//邮件发送成功
    }
    
    /**
     * 发送经过Base64编码后的数据
     * @param src
     */
    public void sendBase64Data(StringBuffer srcData){
        int LEN_CMD_DATA = 76;
        int startIndex = 0;
        int totalLength = 0;
        if(srcData!=null && srcData.length()>0){
            totalLength = srcData.length();
            while(true){
                if(startIndex+LEN_CMD_DATA<totalLength){
                    sendCmd(srcData.substring(startIndex,startIndex+LEN_CMD_DATA));
                    sendCmd(END_FLAG);
                }else{
                    sendCmd(srcData.substring(startIndex,totalLength));
                    sendCmd(END_FLAG);
                    break;
                }
                startIndex = startIndex+LEN_CMD_DATA;
            }
        }
    }
    
    /**
     * 释放所有资源
     *
     */
    public void freeAll(){
        if(inData!=null){
            try {
                inData.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            inData = null;
        }
        
        if(outData!=null){
            try {
                outData.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            outData = null;
        }   
        
        if(clientMailSocket!=null){
            try {
                clientMailSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            clientMailSocket = null;
        }
        
    }
    
    
    /**
     * 读取文件内容
     * @param fileName
     * @return
     */
    public String readFile(String fileName){
        byte[] fileBuffer = new byte[1024];
        int realSize = 0;
        StringBuffer readContent = new StringBuffer();
        try {
            InputStream inFile = new FileInputStream(new File(fileName));
            while(true){
                realSize = inFile.read(fileBuffer);
                if(-1==realSize) break;
                readContent.append(new String(fileBuffer,0,realSize));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return readContent.toString();
    }

    /**
     * Base64编码函数
     * 将指定的字符串编码为Base64格式的字符串
     * @param src
     * @return
     */
    public static String Base64Encode(String src) {
        if (src == null || src.length() == 0)
            return "";
        String EncodingTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        byte[] Buffer = src.getBytes();
        int ReadNow, i, res;
        char[] WriteBuf = new char[4];
        char[] Buf = new char[3];
        String EncodedStr = "";
        int ReadIndex = 0;
        int Len = Buffer.length;
        boolean isEnd;
        int BytesWritten = 0;
        ReadNow = 0;
        do {
            isEnd = false;
            for (i = 0; i < 3; i++) {
                if (ReadIndex >= Len) {
                    isEnd = true;
                    ReadNow = i;
                    break;
                }
                Buf[i] = (char) (((byte) Buffer[ReadIndex]) & 0x00FF);
                ReadIndex = ReadIndex + 1;
            }
            if (isEnd)
                break;
            WriteBuf[0] = EncodingTable.charAt((Buf[0] >> 2) & 0x003F);
            WriteBuf[1] = EncodingTable
                    .charAt(((Buf[0] & 3) << 4 | (Buf[1] >> 4)) & 0x003F);
            WriteBuf[2] = EncodingTable
                    .charAt(((Buf[1] & 15) << 2 | (Buf[2] >> 6)) & 0x003F);
            WriteBuf[3] = EncodingTable.charAt((Buf[2] & 63) & 0x003F);
            for (i = 0; i < 4; i++)
                EncodedStr = EncodedStr + WriteBuf[i];
            BytesWritten = BytesWritten + 4;
            if ((BytesWritten % 76) == 0) {
                EncodedStr = EncodedStr + "";
            }
        } while (ReadNow != 3);
        if (ReadNow < 3) {
            switch (ReadNow) {
            case 1:
                WriteBuf[0] = EncodingTable.charAt((Buf[0] >> 2) & 0x003F);
                WriteBuf[1] = EncodingTable
                        .charAt(((Buf[0] & 3) << 4) & 0x003F);
                WriteBuf[2] = '=';
                WriteBuf[3] = '=';
                for (i = 0; i < 4; i++)
                    EncodedStr = EncodedStr + WriteBuf[i];
                break;
            case 2:
                WriteBuf[0] = EncodingTable.charAt((Buf[0] >> 2) & 0x003F);
                WriteBuf[1] = EncodingTable
                        .charAt(((Buf[0] & 3) << 4 | (Buf[1] >> 4)) & 0x003F);
                WriteBuf[2] = EncodingTable
                        .charAt(((Buf[1] & 15) << 2) & 0x003F);
                WriteBuf[3] = '=';
                for (i = 0; i < 4; i++)
                    EncodedStr = EncodedStr + WriteBuf[i];
                break;
            default:
                break;
            }
        }
        return (EncodedStr);
    }
    
    /**
     * 测试用的main方法.
     * @param args main方法的参数.
     */
    public static void main(String[] args) {
        
        MailTool foxMail = new MailTool("mail.xxx.com",25);//smtp服务器地址
        foxMail.setMailUserName("username@xxx.com");//mail.xxx.com的一个email用户
        foxMail.setMailUserPass("password");//username@xxx.com账户的密码
        foxMail.setMailTo("username@yyy.com");//发送目标email地址
        foxMail.setMailFrom("username@xxx.com");
        foxMail.setMailShowTo("你好");
        foxMail.setMailShowFrom("哈哈");
        foxMail.setMailSubject("hello用中文主题");
        foxMail.setMailBody("welcome for you. 中文呀.aaa \r\n再来一行");

        if(foxMail.sendMail()){
            System.out.println("OK.");
        }else{
            System.out.println("False.");
        }
        foxMail = null;
        
    }
}




当初写这个方法,主要是为了学习下RFC821协议,比较简单,没有作很深入的研究.






















1
0
分享到:
评论

相关推荐

    计算机网络实验二.docx

    RFC 821 [Postel 1982] 规范了SMTP协议,指定了在一个简单TCP连接上,两个MTA(报文传送代理 Message Transfer Agent)如何进行通信。RFC 822 [Crocker 1982] 指定了在两个MTA之间用RFC 821 发送的电子邮件报文的...

    TCPIP协议详解(4-1)

    TCP/IP和Internet 8 2.1 一段历史 8 2.1.1 ARPANET 8 2.1.2 TCP/...RFC的幽默 13 2.3 Internet服务简介 13 2.3.1 Whois和Finger 14 2.3.2 文件传输协议 14 2.3.3 Telnet 14 2.3.4 Email 14 ...

    ipld-eml:与RFC-5322兼容的电子邮件解析器,用于在IPFS上存储数据

    ipld-eml是RFC-5322兼容的IPLD对象格式,用于以节省空间和节省时间的方式存储电子邮件。 TemporalX用作IPFS的接口。 电子邮件在存储到IPFS之前先转换为协议缓冲区对象。 当前有两种存储IPLD对象的方法: 完全作为...

    网络应用程序设计.docx

    RFC822 (7) 接收电子邮件的邮局协议是 POP3 (8) 因特网上使用最多的一种应用是 email (9) SMTP命令的一般的格式命令关键字参数&lt;CRLF&gt; (10) SMTP客户问候SMTP服务器命令格式是 HELO 发送方的主机名&lt;CRLF&gt; ...

    TCP/IP教程TCP/IP基础

    3.6 简单邮件传输协议(SMTP) 26 3.7 网络文件系统(NFS) 26 3.8 简单网络管理协议(SNMP) 27 3.9 TCP/IP和系统结合 27 3.10 内部网概述 28 3.11 小结 28 第二部分 命名和寻址 第4章 IP网络中的名字和地址 29 4.1 IP...

    TCP/IP详解

    3.6 简单邮件传输协议(SMTP) 26 3.7 网络文件系统(NFS) 26 3.8 简单网络管理协议(SNMP) 27 3.9 TCP/IP和系统结合 27 3.10 内部网概述 28 3.11 小结 28 第二部分 命名和寻址 第4章 IP网络中的名字和地址 29 4.1 IP...

    TCP/IP技术大全

    3.6 简单邮件传输协议(SMTP) 26 3.7 网络文件系统(NFS) 26 3.8 简单网络管理协议(SNMP) 27 3.9 TCP/IP和系统结合 27 3.10 内部网概述 28 3.11 小结 28 第二部分 命名和寻址 第4章 IP网络中的名字和地址 29 4.1 IP...

    TCP/IP技术大全(中文PDF非扫描版)

    本书内容十分丰富,几乎涵盖了有关TCP/IP的各个方面,包括开放式通信模型、TCP/IP通信模型、IP网络中的命名和寻址机制、地址解析及反向地址解析协议、DNS域字服务器、WINS、地址发现协议、IPv6、IP网络中的路由协议...

    TCP-IP技术大全

    本书内容十分丰富,几乎涵盖了有关TCP/IP的各个方面,包括开放式通信模型、TCP/IP通信模型、IP网络中的命名和寻址机制、地址解析及反向地址解析协议、DNS域字服务器、WINS、地址发现协议、IPv6、IP网络中的路由协议...

    MailCore案例

    github/mailcore2Licence:BSD平台:iOS设备:iPhone / iPad作者: MailCore team 分类:其他(Others)大小:860.7 kb更新:2013-09-24查看:174 次下载:64 次TAG:mail , email , IMAP , POP , SMTP , 邮件 , ...

    用Delphi2010 实现邮件附件收发功能

    它实现了RFC 1939协议。 在使用TIdPOP3组件时需设置它的几个成员属性。 Host :指定邮件服务器,一般为pop3邮件服务器的地址,如 pop3.126.com。 Username :用户名,也就是邮箱名,如billanking2002@126.com。 ...

    VB网络编程实例

    06.htm SMTP协议简介 (Simple Mail Transfer Protocol) ◆ 07.htm VB5.0 中远程数据库的访问 ◆ 08.htm VB下如何编写CRC校验程序 ◆ 09.htm VB中Winsock控制的UDP协议的使用 ◆ 10....

    电子邮件运行与传输的设计和实现

    本系统是用 java 语言实现的一个 Email客户端,主要用到 java GUI 图形界面设计和 java mail 工具包, 它适用于所有用户,无管理员设置,即可以实现网络邮箱的邮件发送和邮件收取的基本功能,以及建立联系人的功能。

Global site tag (gtag.js) - Google Analytics