用commons-mail发送邮件

Apache的commons-mail对javamail进行了更好的封装,发送邮件更加方便。

引入commons-mail包

使用Maven的方式引入包

    <dependency>
        <groupId>org.apache.commonsgroupId>
        <artifactId>commons-emailartifactId>
        <version>1.5version>
    dependency>

编写邮件实体类和工具类

邮件实体类,MailInfo

package com.ai.dds.email;

import java.util.List;

import org.apache.commons.mail.EmailAttachment;

/**
 * 邮件相关信息
 */
public class MailInfo {
    // 收件人
    private List toAddress = null;
    // 抄送人地址
    private List ccAddress = null;
    // 密送人
    private List bccAddress = null;
    // 附件信息
    private List attachments = null;
    // 邮件主题
    private String subject;
    // 邮件的文本内容
    private String content;

    public List getToAddress() {
        return toAddress;
    }

    public void addToAddress(String toAddress) {
        this.toAddress.add(toAddress);
    }

    public void addToAddress(List toAddress) {
        this.toAddress.addAll(toAddress);
    }

    public void addCcAddress(List ccAddress) {
        if (null != ccAddress && ccAddress.size() > 0)
            this.ccAddress.addAll(ccAddress);
    }

    public List getAttachments() {
        return attachments;
    }

    public void setAttachments(List attachments) {
        this.attachments = attachments;
    }

    public List getBccAddress() {
        return bccAddress;
    }

    public void setBccAddress(List bccAddress) {
        this.bccAddress = bccAddress;
    }

    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 void setToAddress(List toAddress) {
        this.toAddress = toAddress;
    }

    public List getCcAddress() {
        return ccAddress;
    }

    public void setCcAddress(List ccAddress) {
        this.ccAddress = ccAddress;
    }

}

邮件工具类,MailUtil

package com.ai.dds.email;

import java.util.List;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.log4j.Logger;

/**
 * 发送邮件Util
 */
public class MailUtil {
    private static Logger log = Logger.getLogger(MailUtil.class);
    //邮箱发送配置
    private static String mailSmtpAddress = "smtp.163.com";
    private static String mailSmtpPort = "25";
    private static String mailSenderAddress = "[email protected]";
    private static String mailSenderNick = "abc";
    private static String mailSenderUsername = "[email protected]";
    private static String mailSenderPassword = "123456";
    private static boolean mailUseSSL = false;
    private static String mailSslPort = "465";

    /**
     * 发送 邮件方法 (Html格式,支持附件)
     * @return void
     */
    public static boolean sendHtmlEmail(MailInfo mailInfo) {
        boolean sendResult = false;
        try {
            HtmlEmail email = new HtmlEmail();
            email.setCharset("UTF-8");//邮件的字符集  
            // 配置信息
            email.setHostName(mailSmtpAddress);// 邮件服务器域名  
            email.setSmtpPort(Integer.valueOf(mailSmtpPort));// 邮件服务器smtp协议端口  
            email.setSSLOnConnect(mailUseSSL);// 是否启用SSL  
            // 若启用,设置smtp协议的SSL端口号 
            if(mailUseSSL){
                email.setSslSmtpPort(mailSslPort);
            }
            email.setFrom(mailSenderAddress, mailSenderNick);// 发件人地址  
            email.setAuthentication(mailSenderUsername, mailSenderPassword);// 邮箱账户 
            email.setCharset("UTF-8");//邮件的字符集  

            email.setSubject(mailInfo.getSubject());
            email.setHtmlMsg(mailInfo.getContent());

            // 添加附件
            List attachments = mailInfo.getAttachments();
            if (null != attachments && attachments.size() > 0) {
                for (int i = 0; i < attachments.size(); i++) {
                    email.attach(attachments.get(i));
                }
            }

            // 收件人
            List toAddress = mailInfo.getToAddress();
            if (null != toAddress && toAddress.size() > 0) {
                for (int i = 0; i < toAddress.size(); i++) {
                    email.addTo(toAddress.get(i));
                }
            }
            // 抄送人
            List ccAddress = mailInfo.getCcAddress();
            if (null != ccAddress && ccAddress.size() > 0) {
                for (int i = 0; i < ccAddress.size(); i++) {
                    email.addCc(ccAddress.get(i));
                }
            }
            // 邮件模板 密送人
            List bccAddress = mailInfo.getBccAddress();
            if (null != bccAddress && bccAddress.size() > 0) {
                for (int i = 0; i < bccAddress.size(); i++) {
                    email.addBcc(ccAddress.get(i));
                }
            }
            email.send();
            sendResult = true;
            log.info("邮件发送成功");
        } catch (EmailException e) {
            e.printStackTrace();
        }
        return sendResult;
    }

    /**
     * 发送 邮件方法 (非Html格式,支持附件)
     * @return void
     */
    public static boolean sendEmail(MailInfo mailInfo) {
        boolean sendResult = false;
        try {
            MultiPartEmail email = new MultiPartEmail();
            // 配置信息
            email.setHostName(mailSmtpAddress);// 邮件服务器域名  
            email.setSmtpPort(Integer.valueOf(mailSmtpPort));// 邮件服务器smtp协议端口  
            email.setSSLOnConnect(mailUseSSL);// 是否启用SSL  
            // 若启用,设置smtp协议的SSL端口号 
            if(mailUseSSL){
                email.setSslSmtpPort(mailSslPort);
            }
            email.setFrom(mailSenderAddress, mailSenderNick);// 发件人地址  
            email.setAuthentication(mailSenderUsername, mailSenderPassword);// 邮箱账户 
            email.setCharset("UTF-8");//邮件的字符集  

            email.setSubject(mailInfo.getSubject());
            email.setMsg(mailInfo.getContent());

            // 添加附件
            List attachments = mailInfo.getAttachments();
            if (null != attachments && attachments.size() > 0) {
                for (int i = 0; i < attachments.size(); i++) {
                    email.attach(attachments.get(i));
                }
            }

            // 收件人
            List toAddress = mailInfo.getToAddress();
            if (null != toAddress && toAddress.size() > 0) {
                for (int i = 0; i < toAddress.size(); i++) {
                    email.addTo(toAddress.get(i));
                }
            }
            // 抄送人
            List ccAddress = mailInfo.getCcAddress();
            if (null != ccAddress && ccAddress.size() > 0) {
                for (int i = 0; i < ccAddress.size(); i++) {
                    email.addCc(ccAddress.get(i));
                }
            }
            // 邮件模板 密送人
            List bccAddress = mailInfo.getBccAddress();
            if (null != bccAddress && bccAddress.size() > 0) {
                for (int i = 0; i < bccAddress.size(); i++) {
                    email.addBcc(ccAddress.get(i));
                }
            }
            email.send();
            sendResult = true;
            log.info("邮件发送成功");
        } catch (EmailException e) {
            e.printStackTrace();
        }
        return sendResult;
    }

}

上面的邮箱发送配置参数,在实际应用中最好用参数配置的方式

使用MailUtil发送邮件

/**
 * Email发送
 * @param task
 * @param attachFile
 * @return
 */
private boolean SendEmail(Map task, String attachFile) {
    MailInfo mailInfo = new MailInfo();
    try {
        mailInfo.setSubject(task.get("SUBJECT"));

        List toAddress = Arrays.asList(task.get("EMAIL_TO").split(":"));
        mailInfo.setToAddress(toAddress);

        mailInfo.setContent(task.get("SEND_CONTENT"));

        String ccEmail = task.get("CC_EMAIL");
        if(null!=ccEmail&&!ccEmail.equals("")){
            List ccAddress = Arrays.asList(ccEmail.split(":"));
            mailInfo.setCcAddress(ccAddress);
        }

        String bccEmail = task.get("BCC_EMAIL");
        if(null!=bccEmail&&!bccEmail.equals("")){
            List bccAddress = Arrays.asList(bccEmail.split(":"));
            mailInfo.setBccAddress(bccAddress);
        }

        EmailAttachment attachment = new EmailAttachment();
        //附件名字进行编码,不然会乱码
        attachment.setName(MimeUtility.encodeText(StrUtil.getFileName(zipAttachFile)));
        attachment.setPath(attachFile);  
        attachment.setDisposition(EmailAttachment.ATTACHMENT);  
        attachment.setDescription("This is ZIP file"); 

        mailInfo.setAttachments(Arrays.asList(attachment));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return MailUtil.sendHtmlEmail(mailInfo);
}

163邮箱配置

我使用的是163邮箱进行发送的邮件,如果以前没有开通SMTP服务的话,需要登录邮箱进行开启,并设置客户端授权密码
那么邮箱验证的时候输入的就是这个客户端授权密码而不是邮箱登录密码,即setAuthentication的第二个参数。
setAuthentication(mailSenderUsername, mailSenderPassword);


另外,163的邮件的名字不能太长,太长的话显示的就是乱码,据说是13个字。

你可能感兴趣的:(工具)