•  

实现对smtp发送邮件,pop3 imap 接收邮件的封装

2017-12-09

最近需要使用java来实现对邮件的发送,根据自己的设计思想封装了一下,简化邮件的发送,希望大家能用得上。

1、定义一个抽象类,定义邮件通用接口和实现方法。

package com.sl.basic.mail.model;

import java.util.Properties;

/**
 * Created by long on 2017/5/16.
 */
public abstract class Mail  extends Properties {



    public Mail(String protocol){

        setProtocol(protocol);
    }



    public void setProtocol(String protocol){
        if("imap".equals(protocol)||"pop3".equals(protocol)){
            this.put("mail.store.protocol", protocol);
        }
    }

    public String getProtocol(){
        return this.getProperty("mail.store.protocol");
    }


        /**
         * SMTP服务器
         * @param host
         */
    public  abstract void setHost(String host);

    public  abstract String getHost();


    /**
     * 是否需要认证
     * @param auth
     */
    public abstract void setAuth(Boolean auth);

    /**
     * @param port 端口号
     */
    public abstract void setPort(String port);

    public abstract String getPort();


    /**
     * @param user 用户账号
     */
    public  void setUser(String user){
        this.put("mail.user", user);
       // this.user=user;
    }

    public String getUser(){
        return this.getProperty("mail.user");
    }

    /**
     *
     * @param password 密码,或者授权码
     */
    public  void setPassword(String password){
        this.put("mail.password", password);
    }

    public String getPassword(){
        return  this.getProperty("mail.password");
    }
    /**
     * 是否采用SSL协议通道(最好使用SSL,如果使用非SSL且端口使用25,很可能被服务运营商限制收发邮件)
     * @param ssl
     */
    public abstract void setSsl(Boolean ssl);

    public abstract Boolean getSsl();
}


2、定义三个子类( SMTP、POP3、IMAP)

1) SMTP

package com.sl.basic.mail.model;  import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 邮件类型实体
 * Created by long on 2017/5/16.
 */
public class SLSmtp extends Mail {

    /**
     * 发送者,显示的发件人名字
     */
    private String sendName;

    /**
     * 标题
     */
    private String title;
    /**
     * 内容
     */
    private String content;

    /**
     * 接收人
     */
    private List<String> to = new ArrayList<String>();

    public SLSmtp() {
        super("smtp");
        setAuth(true);
        setSsl(true);
        //25:普通端口,经常被封,465:加密端口,要配合ssl使用,一般没有被封
        setPort("465");

    }

    @Override
    public String getHost() {
        return this.getProperty("mail.imap.host");
    }

    /**
     * SMTP服务器
     *
     * @param host
     */
    public void setHost(String host) {
        this.put("mail.smtp.host", host);
    }

    /**
     * 是否需要认证
     *
     * @param auth
     */
    public void setAuth(Boolean auth) {
        this.put("mail.smtp.auth", auth.toString());
    }

    /**
     * @param port 端口号
     */
    public void setPort(String port) {
        if (this.getSsl()){
            this.put("mail.smtp.socketFactory.port", port);
        }else{
            this.put("mail.smtp.port", port);
        }
    }

    @Override
    public String getPort() {
        String port = this.getProperty("mail.smtp.socketFactory.port");
        if (port == null) {
            port = this.getProperty("mail.smtp.port");
        }
        return port;
    }


    /**
     * 是否采用SSL协议通道(最好使用SSL,如果使用非SSL且端口使用25,很可能被服务运营商限制收发邮件)
     *
     * @param ssl
     */
    public void setSsl(Boolean ssl) {
        if (ssl) {
            this.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            String port=getPort();
            if(port!=null) {
                this.put("mail.smtp.socketFactory.port",port);
            }
        } else {
            this.remove("mail.smtp.socketFactory.class");
        }
    }

    @Override
    public Boolean getSsl() {
        return "javax.net.ssl.SSLSocketFactory".equals(this.getProperty("mail.smtp.socketFactory.class"));
    }


    public String getSendName() {
        return this.sendName;
    }

    public void setSendName(String sendName) {
        this.sendName = sendName;
    }

    public String getTitle() {
        return this.title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return this.content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    /**
     * 添加接收人
     *
     * @param to 接收人邮件
     * @author jiangfl
     * @2014-3-20
     */
    public void addTo(String to) {
        this.to.add(to);
    }

    public List<String> getTo() {
        return this.to;
    }

}


2) pop3

package com.sl.basic.mail.model;

import com.sun.org.apache.xpath.internal.operations.Bool;

import java.util.Properties;

/**
 * 邮件类型实体
 * Created by long on 2017/5/16.
 */
public class SLPop3 extends Mail {
    public SLPop3() {
        super("pop3");
    }

    @Override
    public String getHost() {
        return this.getProperty("mail.pop3.host");
    }

    /**
     * SMTP服务器
     *
     * @param host
     */
    public void setHost(String host) {
        this.put("mail.pop3.host", host);
    }

    /**
     * 是否需要认证
     *
     * @param auth
     */
    public void setAuth(Boolean auth) {
        // this.put("mail.pop3.auth",auth.toString());
    }

    @Override
    public String getPort() {
        String port = this.getProperty("mail.pop3.socketFactory.port");
        if (port == null) {
            port = this.getProperty("mail.pop3.port");
        }
        return port;
    }

    /**
     * @param port 端口号
     */
    public void setPort(String port) {
        if (this.getSsl()) {
            this.put("mail.pop3.port", port);
        } else {
            this.put("mail.pop3.socketFactory.port", port);
        }
    }

    @Override
    public Boolean getSsl() {
        return "javax.net.ssl.SSLSocketFactory".equals(this.getProperty("mail.pop3.socketFactory.class"));
    }

    /**
     * 是否采用SSL协议通道(最好使用SSL,如果使用非SSL且端口使用25,很可能被服务运营商限制收发邮件)
     *
     * @param ssl
     */
    public void setSsl(Boolean ssl) {
        if (ssl) {
            this.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            String port=getPort();
            if(port!=null) {
                this.put("mail.pop3.socketFactory.port",port);
            }

        } else {
            this.remove("mail.pop3.socketFactory.class");
        }
    }
}


 3
) imap

package com.sl.basic.mail.model;

import com.sun.org.apache.xpath.internal.operations.Bool;
import org.quartz.SimpleTrigger;

import java.util.Properties;

/**
 * 邮件类型实体
 * Created by long on 2017/5/16.
 */
public class SLImap extends Mail {


    public SLImap() {
        super("imap");
    }

    @Override
    public String getHost() {
        return this.getProperty("mail.imap.host");
    }

    /**
     * SMTP服务器
     *
     * @param host
     */
    public void setHost(String host) {
        this.put("mail.imap.host", host);
    }

    /**
     * 是否需要认证
     *
     * @param auth
     */
    public void setAuth(Boolean auth) {
        this.put("mail.imap.auth", auth.toString());
    }

    @Override
    public Boolean getSsl() {
        return "javax.net.ssl.SSLSocketFactory".equals(this.getProperty("mail.imap.socketFactory.class"));
    }

    /**
     * 是否采用SSL协议通道(最好使用SSL,如果使用非SSL且端口使用25,很可能被服务运营商限制收发邮件)
     *
     * @param ssl
     */
    public void setSsl(Boolean ssl) {
        if (ssl) {
            this.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            String port = getPort();
            if (port != null) {
                this.put("mail.imap.socketFactory.port", port);
            }
        } else {
            this.remove("mail.imap.socketFactory.class");
        }
    }

    @Override
    public String getPort() {
        String port = this.getProperty("mail.imap.socketFactory.port");
        if (port == null) {
            port = this.getProperty("mail.imap.port");
        }
        return port;
    }

    /**
     * @param port 端口号
     */
    public void setPort(String port) {
        if (this.getSsl()) {
            this.put("mail.imap.port", port);
        } else {
            this.put("mail.imap.socketFactory.port", port);
        }
    }


}


3、 定义用户认证类(SLMailAuthenticator
)

/**
 * @desc
 * @2016-11-10
 * @author jiangfl
 * @Copyright:Copyright ShenZhen SL Software Corporation
 */
package com.sl.basic.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * @author jiangfl
 * @desc
 * @2016-11-10
 * @Copyright:Copyright ShenZhen SL Software Corporation
 */
public class SLMailAuthenticator extends Authenticator {
    String userName;
    String pwd;

    public SLMailAuthenticator(String userName, String pwd) {
        this.userName = userName;
        this.pwd = pwd;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, pwd);
    }
}


4、 发送邮件类

package com.sl.basic.mail;
import com.sl.basic.mail.model.Mail;
import com.sl.basic.mail.model.SLPop3;
import com.sl.basic.mail.model.SLSmtp;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeUtility;

/**
 * 很多主机安全对25端口做了限制访问,因此最好不要用25,应该用465端口
 */
public class SLMailSend {

	public void sendEmail(SLSmtp mail) throws Exception {
		try {
			// 使用环境属性和授权信息,创建邮件会话
			Session mailSession = Session.getInstance((Properties)mail, new SLMailAuthenticator(mail.getUser(), mail.getPassword()));
			// 创建邮件消息
			MimeMessage message = new MimeMessage(mailSession);
			// 设置发件人
			InternetAddress form = new InternetAddress(mail.getUser(), mail.getSendName(), "UTF-8");
			message.setFrom(form);

			InternetAddress[] toAddress = new InternetAddress[mail.getTo().size()];
			for (int i = 0; i < mail.getTo().size(); i++) {
				toAddress[i] = new InternetAddress(mail.getTo().get(i));
			}
			message.setRecipients(RecipientType.TO, toAddress);

			// 设置邮件标题
			message.setSubject(mail.getTitle(), "UTF-8");

			// 设置邮件的内容体
			message.setContent(mail.getContent(), "text/html;charset=UTF-8");
			// 最后当然就是发送邮件啦
			Transport.send(message);
			// 早boke项目中,也有一个发送邮件的,但不知道为什么突然发送不了了,有空研究一下
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	private void testQQ() throws Exception {

		SLSmtp mail=new SLSmtp();
		mail.setHost("smtp.qq.com");
		mail.setSendName("jiangfl");
		mail.setUser("1271598645@qq.com");
		mail.setPassword("54143124"); // qq 授权码 nvdicahebdhgfeid
		mail.setPort("465");
		mail.setSsl(true);

		mail.setTitle("八妹,我测试发送邮件");
		mail.setContent("QQ 邮箱测试");
		mail.addTo("2323@qq.com");
		this.sendEmail(mail);
	}

	

	public static void main(String args[]) throws Exception {
		try {

			SLMailSend obj = new SLMailSend();
			//发送邮件测试####
			obj.testQQ();
			System.out.println("ok");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


5、 接收邮件类

package com.sl.basic.mail;


import com.alibaba.dubbo.rpc.service.EchoService;
import com.sl.basic.mail.model.Mail;
import com.sl.basic.mail.model.SLImap;
import com.sl.basic.mail.model.SLPop3;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * 使用POP3协议接收邮件
 */
public class SLMailReceive {

    public static void main(String[] args) throws Exception {
        SLMailReceive mail = new SLMailReceive();
        mail.imapTest();
        mail.pop3Test();
    }


    private void imapTest() throws Exception {
        SLImap mail = new SLImap();
        mail.setProtocol("imap");
        mail.setHost("imap.mail.yahoo.com");
        mail.setPort("143");
        mail.setUser("itmayun@yahoo.com");
        mail.setPassword("121212");
        mail.setSsl(false);
        receive(mail);
    }


    private void pop3Test() throws Exception {
        SLPop3 mail = new SLPop3();
        mail.setProtocol("pop3");
        mail.setHost("pop.mail.yahoo.com");
        mail.setPort("110");
        mail.setUser("itmayun@yahoo.com");
        mail.setPassword("121212");
        mail.setSsl(false);
        receive(mail);
    }


    /**
     * 接收邮件pop3
     */
    public void receive(Mail mail) throws Exception {

        // 创建Session实例对象
        Session session = Session.getInstance(mail);
        Store store = session.getStore(mail.getProtocol());
        store.connect(mail.getHost(), mail.getUser(), mail.getPassword());

        // 获得收件箱
        Folder folder = store.getFolder("INBOX");
        /* Folder.READ_ONLY:只读权限
         * Folder.READ_WRITE:可读可写(可以修改邮件的状态)
         */
        folder.open(Folder.READ_WRITE); //打开收件箱

        // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
        System.out.println("未读邮件数: " + folder.getUnreadMessageCount());

        // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
        System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
        System.out.println("新邮件: " + folder.getNewMessageCount());

        // 获得收件箱中的邮件总数
        System.out.println("邮件总数: " + folder.getMessageCount());

        // 得到收件箱中的所有邮件,并解析
        Message[] messages = folder.getMessages();
        parseMessage(messages);

        //释放资源
        folder.close(true);
        store.close();
    }


    /**
     * 解析邮件
     *
     * @param messages 要解析的邮件列表
     */
    public void parseMessage(Message... messages) throws MessagingException, IOException {
        if (messages == null || messages.length < 1)
            throw new MessagingException("未找到要解析的邮件!");

        // 解析所有邮件
        for (int i = 0, count = messages.length; i < count; i++) {
            MimeMessage msg = (MimeMessage) messages[i];
            System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");
            System.out.println("主题: " + getSubject(msg));
            System.out.println("发件人: " + getFrom(msg));
            System.out.println("收件人:" + getReceiveAddress(msg, null));
            System.out.println("发送时间:" + getSentDate(msg, null));
            System.out.println("是否已读:" + isSeen(msg));
            System.out.println("邮件优先级:" + getPriority(msg));
            System.out.println("是否需要回执:" + isReplySign(msg));
            System.out.println("邮件大小:" + msg.getSize() * 1024 + "kb");
            boolean isContainerAttachment = isContainAttachment(msg);
            System.out.println("是否包含附件:" + isContainerAttachment);
            if (isContainerAttachment) {
                saveAttachment(msg, "c:\\mailtmp\\" + msg.getSubject() + "_"); //保存附件
            }
            StringBuffer content = new StringBuffer(30);
            getMailTextContent(msg, content);
            System.out.println("邮件正文:" + (content.length() > 100 ? content.substring(0, 100) + "..." : content));
            System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");
            System.out.println();
        }
    }

    /**
     * 获得邮件主题
     *
     * @param msg 邮件内容
     * @return 解码后的邮件主题
     */
    public String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
        return MimeUtility.decodeText(msg.getSubject());
    }

    /**
     * 获得邮件发件人
     *
     * @param msg 邮件内容
     * @return 姓名 <Email地址>
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
        String from = "";
        Address[] froms = msg.getFrom();
        if (froms.length < 1)
            throw new MessagingException("没有发件人!");

        InternetAddress address = (InternetAddress) froms[0];
        String person = address.getPersonal();
        if (person != null) {
            person = MimeUtility.decodeText(person) + " ";
        } else {
            person = "";
        }
        from = person + "<" + address.getAddress() + ">";

        return from;
    }

    /**
     * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人
     * <p>Message.RecipientType.TO  收件人</p>
     * <p>Message.RecipientType.CC  抄送</p>
     * <p>Message.RecipientType.BCC 密送</p>
     *
     * @param msg  邮件内容
     * @param type 收件人类型
     * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ...
     * @throws MessagingException
     */
    public String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
        StringBuffer receiveAddress = new StringBuffer();
        Address[] addresss = null;
        if (type == null) {
            addresss = msg.getAllRecipients();
        } else {
            addresss = msg.getRecipients(type);
        }

        if (addresss == null || addresss.length < 1)
            throw new MessagingException("没有收件人!");
        for (Address address : addresss) {
            InternetAddress internetAddress = (InternetAddress) address;
            receiveAddress.append(internetAddress.toUnicodeString()).append(",");
        }

        receiveAddress.deleteCharAt(receiveAddress.length() - 1); //删除最后一个逗号

        return receiveAddress.toString();
    }

    /**
     * 获得邮件发送时间
     *
     * @param msg 邮件内容
     * @return yyyy年mm月dd日 星期X HH:mm
     * @throws MessagingException
     */
    public String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
        Date receivedDate = msg.getSentDate();
        if (receivedDate == null)
            return "";

        if (pattern == null || "".equals(pattern))
            pattern = "yyyy年MM月dd日 E HH:mm ";

        return new SimpleDateFormat(pattern).format(receivedDate);
    }

    /**
     * 判断邮件中是否包含附件
     *
     * @param part
     * @return 邮件中存在附件返回true,不存在返回false
     * @throws MessagingException
     * @throws IOException
     */
    public boolean isContainAttachment(Part part) throws MessagingException, IOException {
        boolean flag = false;
        if (part.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    flag = isContainAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("application") != -1) {
                        flag = true;
                    }

                    if (contentType.indexOf("name") != -1) {
                        flag = true;
                    }
                }

                if (flag) break;
            }
        } else if (part.isMimeType("message/rfc822")) {
            flag = isContainAttachment((Part) part.getContent());
        }
        return flag;
    }

    /**
     * 判断邮件是否已读  www.2cto.com
     *
     * @param msg 邮件内容
     * @return 如果邮件已读返回true, 否则返回false
     * @throws MessagingException
     */
    public boolean isSeen(MimeMessage msg) throws MessagingException {
        return msg.getFlags().contains(Flags.Flag.SEEN);
    }

    /**
     * 判断邮件是否需要阅读回执
     *
     * @param msg 邮件内容
     * @return 需要回执返回true, 否则返回false
     * @throws MessagingException
     */
    public boolean isReplySign(MimeMessage msg) throws MessagingException {
        boolean replySign = false;
        String[] headers = msg.getHeader("Disposition-Notification-To");
        if (headers != null)
            replySign = true;
        return replySign;
    }

    /**
     * 获得邮件的优先级
     *
     * @param msg 邮件内容
     * @return 1(High):紧急  3:普通(Normal)  5:低(Low)
     * @throws MessagingException
     */
    public String getPriority(MimeMessage msg) throws MessagingException {
        String priority = "普通";
        String[] headers = msg.getHeader("X-Priority");
        if (headers != null) {
            String headerPriority = headers[0];
            if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1)
                priority = "紧急";
            else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1)
                priority = "低";
            else
                priority = "普通";
        }
        return priority;
    }

    /**
     * 获得邮件文本内容
     *
     * @param part    邮件体
     * @param content 存储邮件文本内容的字符串
     * @throws MessagingException
     * @throws IOException
     */
    public void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
        //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part) part.getContent(), content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart, content);
            }
        }
    }

    /**
     * 保存附件
     *
     * @param part    邮件中多个组合体中的其中一个组合体
     * @param destDir 附件保存目录
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException,
            FileNotFoundException, IOException {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
            //复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                //获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                //某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();
                    saveFile(is, destDir, decodeText(bodyPart.getFileName()));
                } else if (bodyPart.isMimeType("multipart/*")) {
                    saveAttachment(bodyPart, destDir);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachment((Part) part.getContent(), destDir);
        }
    }

    /**
     * 读取输入流中的数据保存至指定目录
     *
     * @param is       输入流
     * @param fileName 文件名
     * @param destDir  文件存储目录
     * @throws FileNotFoundException
     * @throws IOException
     */
    private void saveFile(InputStream is, String destDir, String fileName)
            throws FileNotFoundException, IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(new File(destDir + fileName)));
        int len = -1;
        while ((len = bis.read()) != -1) {
            bos.write(len);
            bos.flush();
        }
        bos.close();
        bis.close();
    }

    /**
     * 文本解码
     *
     * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
     * @return 解码后的文本
     * @throws UnsupportedEncodingException
     */
    public String decodeText(String encodeText) throws UnsupportedEncodingException {
        if (encodeText == null || "".equals(encodeText)) {
            return "";
        } else {
            return MimeUtility.decodeText(encodeText);
        }
    }
}
申明:本文受法律保护,未经作者同意不得用于商业用途,如转载请说明出处!
评论