All Downloads are FREE. Search and download functionalities are using the official Maven repository.

matrix.boot.common.utils.EmailUtil Maven / Gradle / Ivy

There is a newer version: 2.1.11
Show newest version
package matrix.boot.common.utils;

import com.sun.net.ssl.internal.ssl.Provider;
import matrix.boot.common.exception.ServiceException;
import org.apache.commons.collections4.CollectionUtils;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.net.URL;
import java.security.Security;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 邮件工具
 * @author wangcheng
 */
public class EmailUtil {

    static {
        Security.addProvider(new Provider());
    }

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 服务器地址
     */
    private String server;

    /**
     * 是否ssl连接
     */
    private boolean isSsl = false;

    /**
     * 会话
     */
    private Session session;

    /**
     * 通道
     */
    private Transport transport = null;

    private EmailUtil() {}

    private EmailUtil(String username, String password, String server, Boolean isSsl) {
        AssertUtil.notNullTip(username, "username");
        AssertUtil.notNullTip(password, "password");
        AssertUtil.notNullTip(server, "server");
        this.username = username;
        this.password = password;
        this.server = server;
        if (isSsl != null) {
            this.isSsl = isSsl;
        }
        //端口
        String port = server.split(":").length > 1 ? server.split(":")[1] : null;
        Properties props = System.getProperties();
        props.put("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        if (!this.isSsl) {
            //非安全连接
            props.put("mail.smtp.port", port != null ? port : "25");
            this.session = Session.getInstance(props, (Authenticator) null);
        } else {
            //安全连接
            props.setProperty("mail.host", server.split(":")[0]);
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.ssl.enable", "true");
            props.setProperty("mail.smtp.port", port != null ? port : "465");
            props.setProperty("mail.smtp.socketFactory.port", port != null ? port : "465");
            this.session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        }
        this.session.setDebug(false);
    }

    /**
     * 实例化
     * @param username 用户名
     * @param password 密码
     * @param server 服务器地址
     * @param isSsl 是否安全连接
     * @return 实例
     */
    public static EmailUtil getInstance(String username, String password, String server, Boolean isSsl) {
        return new EmailUtil(username, password, server, isSsl);
    }

    /**
     * 单人发送
     * @param receiver 接收人
     * @param title 标题
     * @param content 内容
     */
    public void sendOne(String receiver, String title, String content) {
        this.sendOne(receiver, title, content, null);
    }

    /**
     * 单人发送
     * @param receiver 接收人
     * @param title 标题
     * @param content 内容
     * @param attachments 附件
     */
    public void sendOne(String receiver, String title, String content, List attachments) {
        AssertUtil.notNullTip(receiver, "receiver");
        List receivers = new ArrayList<>();
        receivers.add(receiver);
        this.send(receivers, null, null, title, content, attachments);
    }

    /**
     * 多人发送
     * @param receivers 接收人
     * @param title 标题
     * @param content 内容
     */
    public void sendMany(List receivers, String title, String content) {
        this.sendMany(receivers, null, null, title, content, null);
    }

    /**
     * 多人发送
     * @param receivers 接收人
     * @param ccReceivers 抄送人
     * @param bccReceivers 密送人
     * @param title 标题
     * @param content 内容
     */
    public void sendMany(List receivers, List ccReceivers, List bccReceivers, String title, String content) {
        this.send(receivers, ccReceivers, bccReceivers, title, content, null);
    }

    /**
     * 多人发送
     * @param receivers 接收人
     * @param title 标题
     * @param content 内容
     * @param attachments 附件
     */
    public void sendMany(List receivers, String title, String content, List attachments) {
        this.sendMany(receivers, null, null, title, content, attachments);
    }

    /**
     * 多人发送
     * @param receivers 接收人
     * @param ccReceivers 抄送人
     * @param bccReceivers 密送人
     * @param title 标题
     * @param content 内容
     * @param attachments 附件
     */
    public void sendMany(List receivers, List ccReceivers, List bccReceivers, String title, String content, List attachments) {
        this.send(receivers, ccReceivers, bccReceivers, title, content, attachments);
    }

    /**
     * 发送邮件
     * @param receivers 接收人
     * @param ccReceivers 抄送人
     * @param bccReceivers 密送人
     * @param title 邮件标题
     * @param content 邮件内容
     * @param attachments 附件信息
     */
    private void send(List receivers, List ccReceivers, List bccReceivers, String title, String content, List attachments) {
        AssertUtil.state(!CollectionUtils.isEmpty(receivers), "receivers don't be null");
        try {
            MimeMessage message = new MimeMessage(this.session);
            message.setFrom(new InternetAddress(this.username));
            message.setSentDate(DateUtil.convertDate(DateUtil.getNow()));
            //接收人
            Address[] address = new Address[receivers.size()];
            for (int i = 0; i < receivers.size(); ++i) {
                address[i] = new InternetAddress(receivers.get(i));
            }
            message.addRecipients(Message.RecipientType.TO, address);
            //抄送人
            if (!CollectionUtils.isEmpty(ccReceivers)) {
                Address[] ccAddress = new Address[ccReceivers.size()];
                for (int i = 0; i < ccReceivers.size(); ++i) {
                    ccAddress[i] = new InternetAddress(ccReceivers.get(i));
                }
                message.addRecipients(Message.RecipientType.CC, ccAddress);
            }
            //密送人
            if (!CollectionUtils.isEmpty(bccReceivers)) {
                Address[] bccAddress = new Address[bccReceivers.size()];
                for (int i = 0; i < bccReceivers.size(); ++i) {
                    bccAddress[i] = new InternetAddress(bccReceivers.get(i));
                }
                message.addRecipients(Message.RecipientType.BCC, bccAddress);
            }
            //邮件主题
            message.setSubject(MimeUtility.encodeText(title, "gb2312", "B"));
            Multipart multipart = new MimeMultipart();
            //邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(content, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);
            //邮件附件
            if (attachments != null && !attachments.isEmpty()) {
                for (URL url : attachments) {
                    BodyPart attachmentBodyPart = new MimeBodyPart();
                    DataSource source = new URLDataSource(url);
                    attachmentBodyPart.setDataHandler(new DataHandler(source));
                    attachmentBodyPart.setFileName(MimeUtility.encodeWord(url.getFile()));
                    multipart.addBodyPart(attachmentBodyPart);
                }
            }
            message.setContent(multipart);
            message.saveChanges();
            if (!isSsl) {
                transport = this.session.getTransport();
                transport.connect(this.server, this.username, this.password);
                transport.sendMessage(message, message.getAllRecipients());
            } else {
                Transport.send(message, message.getAllRecipients());
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        } finally {
            if (transport != null) {
                try {
                    transport.close();
                } catch (MessagingException ignored) {
                }
            }
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy