用commons-mail发送邮件

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

引入commons-mail包

使用Maven的方式引入包

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-email</artifactId>
        <version>1.5</version>
    </dependency>

编写邮件实体类和工具类

邮件实体类,MailInfo

package com.ai.dds.email;

import java.util.List;

import org.apache.commons.mail.EmailAttachment;

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

    public List<String> getToAddress() {
        return toAddress;
    }

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

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

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

    public List<EmailAttachment> getAttachments() {
        return attachments;
    }

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

    public List<String> getBccAddress() {
        return bccAddress;
    }

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

    public List<String> getCcAddress() {
        return ccAddress;
    }

    public void setCcAddress(List<String> 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 = "abc@163.com";
    private static String mailSenderNick = "abc";
    private static String mailSenderUsername = "abc@163.com";
    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<EmailAttachment> attachments = mailInfo.getAttachments();
            if (null != attachments && attachments.size() > 0) {
                for (int i = 0; i < attachments.size(); i++) {
                    email.attach(attachments.get(i));
                }
            }

            // 收件人
            List<String> toAddress = mailInfo.getToAddress();
            if (null != toAddress && toAddress.size() > 0) {
                for (int i = 0; i < toAddress.size(); i++) {
                    email.addTo(toAddress.get(i));
                }
            }
            // 抄送人
            List<String> ccAddress = mailInfo.getCcAddress();
            if (null != ccAddress && ccAddress.size() > 0) {
                for (int i = 0; i < ccAddress.size(); i++) {
                    email.addCc(ccAddress.get(i));
                }
            }
            // 邮件模板 密送人
            List<String> 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<EmailAttachment> attachments = mailInfo.getAttachments();
            if (null != attachments && attachments.size() > 0) {
                for (int i = 0; i < attachments.size(); i++) {
                    email.attach(attachments.get(i));
                }
            }

            // 收件人
            List<String> toAddress = mailInfo.getToAddress();
            if (null != toAddress && toAddress.size() > 0) {
                for (int i = 0; i < toAddress.size(); i++) {
                    email.addTo(toAddress.get(i));
                }
            }
            // 抄送人
            List<String> ccAddress = mailInfo.getCcAddress();
            if (null != ccAddress && ccAddress.size() > 0) {
                for (int i = 0; i < ccAddress.size(); i++) {
                    email.addCc(ccAddress.get(i));
                }
            }
            // 邮件模板 密送人
            List<String> 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<String, String> task, String attachFile) {
    MailInfo mailInfo = new MailInfo();
    try {
        mailInfo.setSubject(task.get("SUBJECT"));

        List<String> 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<String> ccAddress = Arrays.asList(ccEmail.split(":"));
            mailInfo.setCcAddress(ccAddress);
        }

        String bccEmail = task.get("BCC_EMAIL");
        if(null!=bccEmail&&!bccEmail.equals("")){
            List<String> 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个字。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值