发送邮件的工具类

 

发送邮件的工具类以及发送邮件的示例代码,支持发送html标签,和发送附件。依赖commons-emailmail两个jar包。

/**
 * 发送邮件Util
 */
public final class MailUtil {
    //发送邮件的主机
    private static String mailServerHost = "smtp.126.com";
    //发件人邮箱
    private static String mailSenderAddress = "发件邮箱地址@126.com";
    //发件人昵称
    private static String mailSenderNick = "发件人昵称";
    //发件人使用的账号
    private static String mailSenderUsername = "发件邮箱地址@126.com";
    //登陆发件主机的密码(或授权码)
    private static String mailSenderPassword = "授权码";
    /**
     * 发送 邮件方法 (Html格式,支持附件)
     * 
     * @return void
     */
    public static final boolean sendEmail(MailInfo mailInfo) {
         
        try {
            HtmlEmail email = new HtmlEmail();
            // 配置发送邮件的主机
            email.setHostName(mailServerHost);
            // 配置发送者地址和昵称
            email.setFrom(mailSenderAddress,mailSenderNick);
            // 配置用于登陆发送邮件主机的账号和登陆密码(或授权码)
            email.setAuthentication(mailSenderUsername,mailSenderPassword);
            // 配置邮件使用的字符集
            email.setCharset("UTF-8");
            // 设置启用SSL连接
            email.setSSLOnConnect(true);
            //设置邮件主题
            email.setSubject(mailInfo.getSubject());
            //设置邮件内容
            email.setHtmlMsg(mailInfo.getContent());
            //设置当邮件客户端不能显示HTML标签时的提示语句
            email.setTextMsg("您的邮件客户端不支持HTML标签(Your email client does not support HTML messages)");
            // 添加附件
            List<EmailAttachment> attachments = mailInfo.getAttachments();
            if (!attachments.isEmpty()) {
                for (EmailAttachment emailAttachment : attachments) {
                     email.attach(emailAttachment);
                }
            }
            // 添加收件人
            Set<String> toAddress = mailInfo.getToAddress();
            if (!toAddress.isEmpty()) {
                System.out.print("收件人:");
                for (String string : toAddress) {
                    email.addTo(string);
                    System.out.print(string+"\t");
                }
                System.out.println();
            }
            // 添加抄送人
            Set<String> ccAddress = mailInfo.getCcAddress();
            if (!ccAddress.isEmpty()) {
                for (String string : ccAddress) {
                    email.addCc(string);
                }
            }
            //发送邮件
            email.send();
            System.out.println("邮件发送成功!");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return false;
    }
    /**
     * 根据邮件主题和收件人,创建一封邮件对象
     * @param subject 邮件主题
     * @param toAddress 收件人
     * @return
     */
    public static final MailInfo createEmail(String subject,String toAddress) {
        return new MailInfo(subject,toAddress);
    }
    /**
     * 封装一封邮件信息的类
     */
    public static class MailInfo {
        // 收件人
        private Set<String> toAddress = new HashSet<>();
        // 抄送人地址
        private Set<String> ccAddress = new HashSet<>();
        // 附件信息
        private List<EmailAttachment> attachments = new ArrayList<>();
        // 邮件主题
        private String subject;
        // 邮件的文本内容
        private StringBuffer content = new StringBuffer();
        private MailInfo(String subject,String toAddress) {
            this.subject = subject;
            this.toAddress.add(toAddress.trim());
        }
        /**
         * 添加收件人
         * @param toAddress
         */
        public void addToAddress(String... toAddress) {
            for (String string : toAddress) {
                this.toAddress.add(string.trim());
            }
        }
        /**
         * 添加抄送人
         * @param ccAddress
         */
        public void addCcAddress(String... ccAddress) {
            for (String string : ccAddress) {
                this.ccAddress.add(string.trim());
            }
        }
        /**
         * 添加本地文件为附件
         * @param aPath:附件路径
         * @param aName:附件名字
         * @param description:附件描述
         */
        public void addAttachment(String aPath,String aName,String description) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setName(aName);
            attachment.setPath(aPath);
            attachment.setDescription(description);
            this.attachments.add(attachment);
        }
        /**
         * 添加远程文件为附件
         * @param aUrl:附件资源的路径
         * @param aName:附件的名字
         * @param description:附件的描述
         */
        public void addAttachment(URL aUrl,String aName,String description) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setName(aName);
            attachment.setURL(aUrl);
            attachment.setDescription(description);
            this.attachments.add(attachment);
        }
        public void setSubject(String subject) {
            this.subject = subject;
        }
        public void addContent(String content) {
            this.content.append(content);
        }
        public Set<String> getToAddress() {
            return toAddress;
        }
        public Set<String> getCcAddress() {
            return ccAddress;
        }
        public List<EmailAttachment> getAttachments() {
            return attachments;
        }
        public String getSubject() {
            return subject==null?"快学大数据":subject;
        }
        public String getContent() {
            return content.toString();
        }
    }
}

 

 

发送邮件的测试类:

import java.net.MalformedURLException;
import java.net.URL;

import com.kuaixueit.utils.MailInfo;
import com.kuaixueit.utils.MailUtil;

public class EmailTest {
    public static void main(String[] args) throws MalformedURLException {
        //创建一个MailInfo对象,用来表示要发送的邮件
        MailUtil.MailInfo mail = MailUtil.createEmail("这是一封测试邮件","收件邮箱");//设置邮件内容
        mail.addContent("<h1 style='color:red'>这是一封来自快学大数据的生日问候!</h1>");
        //往邮件中添加一个超链接
        mail.addContent("<a href=\"http://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3&rsv_spt=1&rsv_iqid=0xec7ce4b000048f84&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=baiduhome_pg&rsv_enter=1&oq=126%25E9%2582%25AE%25E7%25AE%25B1%25E7%2599%25BB%25E9%2599%2586&rsv_t=15dbsR8%2FkP5G1qSGIPgK0dFaQC5SrqmpqaBpPsEYpnYTWNvfPcPZtSwSJjhtxQq5c4po&inputT=2167&rsv_pq=ca7998930006803d&rsv_sug3=9&rsv_sug1=9&rsv_sug7=101&bs=126%E9%82%AE%E7%AE%B1%E7%99%BB%E9%99%86\">点我查看美女</a><br>");
        mail.addContent("<img src=\"https://www.baidu.com/img/bd_logo1.png?where=super\">");
        //往邮件中添加一个附件,附件是本地文件
        mail.addAttachment("F:\\pic\\3c560cf458034c21b54c5b6a77120045.jpg", "美女图片.jpg", "这是送给你的生日福利");
        //往邮件中添加一个附件,附件是一个远程图片
        mail.addAttachment(new URL("https://www.baidu.com/img/bd_logo1.png?where=super"), "美女图片2.jpg", "这是送给你的生日福利");
        //调用工具类发送邮件
        MailUtil.sendEmail(mail);
    }
}

收件箱收到的邮件:

 

posted on 2018-05-18 16:46  大别山人  阅读(301)  评论(0编辑  收藏  举报