Java 发送邮件工具类

package com.test.common.util.mail;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MailInfo {
    
    private String from;
    private String to;
    private String cc;
    private String bcc;
    private String subject;
    private String content;
    
    private String sendServer;
    private String sendUser;
    private String sendPass;
    private boolean needAuth = false;
    private String protocol;
    private Long port;
    
    private List<String> attachFiles;
    
    private Date sendDate;
    private List<String> attachFileNames;
    private String mailFileName;
    
    public MailInfo(){
        this.attachFiles = new ArrayList<String>();
        this.attachFileNames = new ArrayList<String>();
    }
    
    public String getMailInfo(){
        return("   from: " + this.getFrom() + "\n" +
               "     to: " + this.getTo() + "\n" +
               "     cc: " + this.getCc() + "\n" +
               "    bcc: " + this.getBcc() + "\n" +
               "Subject: " + this.getSubject() + "\n" +
               "Content: " + "\n" + this.getContent()
                );
    }
    
    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 getCc() {
        return cc;
    }

    public void setCc(String cc) {
        this.cc = cc;
    }

    public String getBcc() {
        return bcc;
    }

    public void setBcc(String bcc) {
        this.bcc = bcc;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

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

    public String getSendServer() {
        return sendServer;
    }

    public void setSendServer(String sendServer) {
        this.sendServer = sendServer;
    }

    public String getSendUser() {
        return sendUser;
    }

    public void setSendUser(String sendUser) {
        this.sendUser = sendUser;
    }

    public String getSendPass() {
        return sendPass;
    }

    public void setSendPass(String sendPass) {
        this.sendPass = sendPass;
    }

    public boolean isNeedAuth() {
        return needAuth;
    }

    public void setNeedAuth(boolean needAuth) {
        this.needAuth = needAuth;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public Long getPort() {
        return port;
    }

    public void setPort(Long port) {
        this.port = port;
    }

    public List<String> getAttachFiles() {
        return attachFiles;
    }

    public void setAttachFiles(List<String> attachFiles) {
        this.attachFiles = attachFiles;
    }

    public Date getSendDate() {
        return sendDate;
    }

    public void setSendDate(Date sendDate) {
        this.sendDate = sendDate;
    }

    public List<String> getAttachFileNames() {
        return attachFileNames;
    }

    public void setAttachFileNames(List<String> attachFileNames) {
        this.attachFileNames = attachFileNames;
    }

    public String getMailFileName() {
        return mailFileName;
    }

    public void setMailFileName(String mailFileName) {
        this.mailFileName = mailFileName;
    }
}

package com.test.common.util.mail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.test.common.util.file.FileUtils;

/**
 *
 * 类描述 :用于Email发送、接收的工具类。
 *
 */
public class MailUtils {
    
    public final static String PROTOCOL_SMTP = "smtp";
    public final static String PROTOCOL_POP3 = "pop3";
    public final static String PROTOCOL_IMAP = "imap";
    
    public final static String ERROR_NOMAILTO = "没有指定收件人";
    public final static String ERROR_NOSUBJECT = "没有指定邮件主题";
    public final static String ERROR_NOMAILSERVER = "没有指定邮件服务器";
    public final static String ERROR_NOUSER = "没有指定登录邮箱的用户";
    
    private static Authenticator getAuthenticator(String user,String pass){
        class SmtpAuth extends Authenticator {
            private String username,password;    
                
            public SmtpAuth(String username,String password){    
                this.username = username;     
                this.password = password;     
            }    
            protected PasswordAuthentication getPasswordAuthentication() {    
                return new PasswordAuthentication(username,password);    
            }  
        }
        return(new SmtpAuth(user, pass));
    }
    
    /**
     * 发送邮件
     *
     * @param toEmailBox
     *            收件人邮箱
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     * @param attachs
     *            附件列表
     * @return void
     * @throws Exception
     */
    public static void sendEmail(MailInfo mailInfo) throws Exception {
        
        if(mailInfo.getTo() == null || mailInfo.getTo().trim().equals("")){
            throw new Exception(ERROR_NOMAILTO);
        }
        if(mailInfo.getSubject() == null || mailInfo.getSubject().equals("")){
            throw new Exception(ERROR_NOSUBJECT);
        }
        
        if(!MailUtils.PROTOCOL_SMTP.equalsIgnoreCase(mailInfo.getProtocol()) ||
           !MailUtils.PROTOCOL_IMAP.equalsIgnoreCase(mailInfo.getProtocol())){
            mailInfo.setProtocol(MailUtils.PROTOCOL_SMTP);
        }
        
        Properties props = System.getProperties();
        props.put("mail.smtp.host", mailInfo.getSendServer());
        props.put("mail.smtp.auth", mailInfo.isNeedAuth()?"true":"false");
        Authenticator smtpAuth = getAuthenticator(mailInfo.getSendUser(),  
mailInfo.getSendPass());
        Session session = Session.getInstance(props, smtpAuth);

        MimeMessage mimeMsg = new MimeMessage(session);
        MimeMultipart multipart = new MimeMultipart();
        
        mimeMsg.setSubject(mailInfo.getSubject());
        
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent("" + mailInfo.getContent(),  
"text/html;charset=GB2312");
        multipart.addBodyPart(bodyPart);
        
        if(mailInfo.getAttachFiles() != null){
            for(String f:mailInfo.getAttachFiles()){
                File file = new File(f);
                if(!file.exists()){
                    throw new Exception("附件【" + f + "】不存在.");
                }
                MimeBodyPart mbp = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(file);
                mbp.setDataHandler(new DataHandler(fds));
                mbp.setFileName(fds.getName());
                multipart.addBodyPart(mbp);
            }
        }
        
        mimeMsg.addFrom(InternetAddress.parse(mailInfo.getFrom()));
        mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse
(mailInfo.getTo()));
        if(mailInfo.getCc()!=null && !mailInfo.getCc().trim().equals("")){
            mimeMsg.setRecipients(Message.RecipientType.CC,  
InternetAddress.parse(mailInfo.getCc()));
        }
        if(mailInfo.getBcc()!=null && !mailInfo.getBcc().trim().equals("")){
            mimeMsg.setRecipients(Message.RecipientType.BCC,  
InternetAddress.parse(mailInfo.getBcc()));
        }
        mimeMsg.setSentDate(new Date());
        mimeMsg.setContent(multipart);
        mimeMsg.saveChanges();
        //session.setDebug(true);                 // 是否在控制台显
示debug信息
        Transport transport = session.getTransport(mailInfo.getProtocol());
        transport.connect(mailInfo.getSendServer(),mailInfo.getSendUser(),  
mailInfo.getSendPass());
        transport.sendMessage(mimeMsg, mimeMsg.getRecipients
(Message.RecipientType.TO));
        transport.close();
    }    
    
    /**
     * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中: 解析邮件:主要是根据
MimeType类型的不同执行不同的操作,一步一步的解析
     *
     * @param part
     * @throws Exception
     */
    private static String getMailContent(Part part) throws Exception {
        String result = "";
        String contenttype;
        contenttype = part.getContentType();
        int nameindex = contenttype.indexOf("name");
        boolean conname = false;
        if (nameindex != -1) {
            conname = true;
        }
        if (part.isMimeType("text/plain") && !conname) {
            result = result + (String) part.getContent();
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int counts = multipart.getCount();
            for (int i = 0; i < counts; i++) {
                result = result + getMailContent(multipart.getBodyPart
(i));
            }
        } else if (part.isMimeType("message/rfc822")) {
            result = result + getMailContent((Part) part.getContent());
        }
        return(result);
    }
    
    private static String getAddress(Address[] addrs){
        String result = "";
        if(addrs == null || addrs.length == 0){
            return result;
        }
        for(Address addr: addrs){
            InternetAddress iaddr = (InternetAddress)addr;
            String m = iaddr.getAddress();
            result = result + ',' + m;
        }
        if(!"".equals(result)){
            result = result.substring(1);
        }
        return result;
    }
    
    /**
     * 保存文件到指定目录里
     *
     * @param fileName
     * @param in
     * @param path
     * @throws Exception
     */
    private static void saveFile(String fileName, InputStream in) throws Exception {
        OutputStream os = new FileOutputStream(fileName,true);
        try {
            byte[] buf = new byte[4096];
            while(true){
                int cnt = in.read(buf);
                if(cnt > -1){
                    os.write(buf, 0, cnt);
                }
                if(cnt < buf.length){
                    break;
                }
            }
        } finally {
            os.flush();
            os.close();
        }
    }

    /**
     * 保存附件
     *
     * @param part
     * @throws Exception
     */
    private static void extractAttachMent(Part part,List<String>  
fileNames,List<String> files,String tempPath) throws Exception {
        String fileName = "";
        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                BodyPart mpart = mp.getBodyPart(i);
                String disposition = mpart.getDisposition();
                if ((disposition != null)
                        && ((disposition.equals(Part.ATTACHMENT))  
|| (disposition.equals(Part.INLINE)))) {
                    fileName = mpart.getFileName();
                    fileName = new String(mpart.getFileName
().getBytes("ISO-8859-1"), "utf-8");
                    //if (fileName.toLowerCase().indexOf("utf-8") !=  
-1) {
                        fileName = MimeUtility.decodeText
(fileName);
                    //}
                    fileNames.add(fileName);
                    String tfile = FileUtils.getTempFile(tempPath,  
"mail", fileName.substring(fileName.lastIndexOf(".")));
                    files.add(tfile);
                    saveFile(tfile, mpart.getInputStream());
                } else if (mpart.isMimeType("multipart/*")) {
                    extractAttachMent(mpart,fileNames,files,tempPath);
                } else {
                    fileName = mpart.getFileName();
                    if(fileName != null){
                        //if (fileName.toLowerCase().indexOf("utf
-8") != -1) {
                            fileName = MimeUtility.decodeText
(fileName);
                        //}
                        fileNames.add(fileName);
                        String tfile = FileUtils.getTempFile
(tempPath, "mail", fileName.substring(fileName.lastIndexOf(".")));
                        files.add(tfile);
                        saveFile(tfile, mpart.getInputStream());
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            extractAttachMent((Part) part.getContent
(),fileNames,files,tempPath);
        }
    }

    public static List<MailInfo> receiveMails(String mailServer,Long serverPort,String  
protocol,String user,String pass,String tempPath,boolean isdelete) throws Exception{
        //参数检查
        if(mailServer == null || "".equals(mailServer.trim())){
            throw new Exception(ERROR_NOMAILSERVER);
        }
        if(serverPort == null || serverPort.intValue() <= 0){
            serverPort = new Long(110);
        }
        if(protocol == null || "".equals(protocol.trim())){
            protocol = "pop3";
        }
        if(user == null || "".equals(user.trim())){
            throw new Exception(ERROR_NOUSER);
        }
        if(tempPath == null || "".equals(tempPath.trim())){
            tempPath = System.getProperty("java.io.tmpdir");
        }
        File f = new File(tempPath);
        f.mkdirs();
        
        //准备收邮件
        List<MailInfo> mails = new ArrayList<MailInfo>();
        
        Properties props = System.getProperties();
        props.put("mail.smtp.host", mailServer);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, null);
        URLName urln = new URLName(protocol, mailServer, serverPort.intValue(),  
null,user, pass);
        
        //接收邮件并进行处理
        Store store = session.getStore(urln);
        try{
            store.connect();
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);
            Message[] messages = folder.getMessages();
            
            if (messages != null){
              for(int i = 0; i < messages.length; i++){
                Message msg =messages[i];
                MailInfo mailInfo = new MailInfo();
                mailInfo.setContent(getMailContent((Part)msg));
                mailInfo.setSubject(MimeUtility.decodeText(msg.getSubject
()));
                mailInfo.setFrom(getAddress(msg.getFrom()));
                mailInfo.setTo(getAddress(msg.getRecipients
(Message.RecipientType.TO)));
                mailInfo.setCc(getAddress(msg.getRecipients
(Message.RecipientType.CC)));
                mailInfo.setBcc(getAddress(msg.getRecipients
(Message.RecipientType.BCC)));
                try {
                    mailInfo.setSendDate(msg.getSentDate());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                //备份邮件
                mailInfo.setMailFileName(FileUtils.getTempFile(tempPath,  
"mail", ".eml"));
                OutputStream fo = new FileOutputStream
(mailInfo.getMailFileName());
                try{
                    ((Part)msg).writeTo(fo);
                }finally{
                    fo.close();
                }
                
                extractAttachMent((Part)msg,mailInfo.getAttachFileNames
(),mailInfo.getAttachFiles(),tempPath);
                if(isdelete){
                    msg.setFlag(Flags.Flag.DELETED, true);
                }
                mails.add(mailInfo);
            }
            }
            folder.close(true);
        }finally{
            store.close();
        }
        return(mails);
    }
    
    public static void main(String[] args) throws Exception {
        MailInfo mailInfo = new MailInfo();
        String tempPath="E:\\workspace\\test\\temp";
        InputStream fis = new FileInputStream
("E:\\workspace\\test\\mail8063.eml");
        Session mailSession = Session.getDefaultInstance(System.getProperties(),  
null);
        MimeMessage msg = new MimeMessage(mailSession, fis);
        extractAttachMent((Part)msg,mailInfo.getAttachFileNames
(),mailInfo.getAttachFiles(),tempPath);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值