发送邮件的工具类

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

封装邮件内容的Java类:

import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.mail.EmailAttachment;

/**
 * 封装发送的邮件的信息,包括收件人、抄送人、附件、邮件主题和内容
 * @author 彭锋
 * @2018年5月18日 下午4:38:39
 */
public 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();
    /**
     * 添加收件人
     * @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;
    }
    public String getContent() {
        return content.toString();
    }
}

发送邮件的工具类:

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

/**
 * 
 * 发送邮件Util
 * @author 彭锋
 * @2018年5月18日 下午4:39:46
 */
public 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 void sendEmail(MailInfo mailInfo) {
         
        try {
            HtmlEmail email = new HtmlEmail();
            // 配置邮件使用的字符集
            email.setCharset("UTF-8");
            // 配置发送邮件的主机
            email.setHostName(mailServerHost);
            // 配置发送者地址和昵称
            email.setFrom(mailSenderAddress,mailSenderNick);
            // 配置用于登陆发送邮件主机的账号和登陆密码(或授权码)
            email.setAuthentication(mailSenderUsername,mailSenderPassword);
            // 设置启用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("邮件发送成功!");
        } catch (EmailException e) {
            e.printStackTrace();
        } 
    }
}

发送邮件的测试类:

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对象,用来表示要发送的邮件
        MailInfo mail = new MailInfo();
        //设置收件人
        mail.addToAddress("[email protected]");
        //设置邮件的主题
        mail.setSubject("这是一封测试邮件");
        //设置邮件内容
        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);
    }
}

收件箱收到的邮件:

猜你喜欢

转载自www.cnblogs.com/pf1988/p/9056892.html