邮箱工具类

本篇文章是邮箱工具笔记,包含普通邮件/TLS/SSL

添加附件,将资源文件加载到内存中:

        try {
            InputStream is = this.getClass().getClassLoader().getResourceAsStream(StringUtils.join("file", StringPool.SLASH, "验证码示例.png"));
            File tempFile = File.createTempFile("temp", null);
            Files.copy(is, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            log.error("【发送验证码】{} 获取验证码示例附件失败", username, e);
        }

邮箱工具类:

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;


@Slf4j
@UtilityClass
public class EmailUtils {

    /**
     * TLS协议,2.8.0需求:使用配置文件统一配置
     *
     * @return true:支持
     */
    public static boolean enableTLS() {
        Environment environment = SpringContextUtils.getBean(Environment.class);
        String property = environment.getProperty("server.mail.starttls.enable");
        return StringUtils.equals("true", property);
    }

    /**
     * SSL协议,2.8.0需求:使用配置文件统一配置
     *
     * @return true:支持
     */
    public static boolean enableSSL() {
        Environment environment = SpringContextUtils.getBean(Environment.class);
        String property = environment.getProperty("server.mail.ssl.enable");
        return StringUtils.equals("true", property);
    }

    public static Properties getProperties(MailConfigModel configModel) {
        String protocol = configModel.getProtocol();
        final String prefix = "mail.";
        Properties prop = new Properties();
        prop.setProperty("mail.transport.protocol", protocol);
        prop.setProperty(prefix + protocol + ".host", configModel.getHost());
        prop.setProperty(prefix + protocol + ".auth", "true");
        if (enableTLS()) {
            log.info("【发送邮件】开启TLS协议");
            prop.setProperty(prefix + protocol + ".starttls.enable", "true");
            prop.setProperty(prefix + protocol + ".port", configModel.getPort().toString());
        } else if (enableSSL()) {
            log.info("【发送邮件】开启SSL协议");
            prop.setProperty(prefix + protocol + ".socketFactory.port", configModel.getPort().toString());
            prop.setProperty(prefix + protocol + ".socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            prop.setProperty(prefix + protocol + ".ssl.enable", "true");
        } else {
            log.info("【发送邮件】未开启加密协议");
            prop.setProperty(prefix + protocol + ".port", configModel.getPort().toString());
        }
        return prop;
    }

    private static Session getSession(MailConfigModel configModel, Properties prop) {
        Session session = Session.getInstance(prop, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                // 发件人邮件用户名、授权码
                return new PasswordAuthentication(configModel.getEmail(), configModel.getPassword());
            }
        });
        session.setDebug(true);
        return session;
    }

    private static MimeMessage getMessage(MailConfigModel configModel, String subject, String to, InternetAddress[] cc, Session session) throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(configModel.getEmail(), configModel.getUsername(), "utf-8"));
        message.setRecipients(Message.RecipientType.TO, generatedAddress(to));
        message.setRecipients(Message.RecipientType.CC, cc);
        message.setSubject(subject);
        message.setSentDate(new Date());
        return message;
    }

    private Address[] generatedAddress(String emailList) throws UnsupportedEncodingException {
        String[] split = emailList.split(";");
        Address[] addresses = new Address[split.length];
        for (int i = 0; i < split.length; i++) {
            String emailAddress = split[i];
            addresses[i] = new InternetAddress(emailAddress, emailAddress, "utf-8");
        }
        return addresses;
    }

    public static void sendMail(MailConfigModel configModel, String subject, String text, String to, InternetAddress... cc) {
        log.info("发送邮件 email:{}", to);
        Transport trans = null;
        try {
            // 获取配置
            Properties prop = getProperties(configModel);

            // 获取session
            Session session = getSession(configModel, prop);

            // 创建邮件
            MimeMessage message = getMessage(configModel, subject, to, cc, session);

            // 设置文本
            message.setContent(text, "text/html;charset=utf-8");

            // 发送
            message.saveChanges();
            trans = session.getTransport();
            trans.connect();
            trans.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            log.error("邮件发送失败", e);
            throw new DataTunnelWebException(e.getMessage(), e);
        } finally {
            if (trans != null) {
                try {
                    trans.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void sendMail(MailConfigModel configModel, String subject, String text, File file, String fileName, String to, InternetAddress... cc) throws Exception {
        log.info("发送邮件 email:{}", to);
        Transport trans = null;
        try {
            // 获取配置
            Properties prop = getProperties(configModel);

            // 获取session
            Session session = getSession(configModel, prop);

            // 创建邮件
            Message message = getMessage(configModel, subject, to, cc, session);

            // 创建复合消息
            Multipart multipart = new MimeMultipart();
            message.setContent(multipart);

            // 创建邮件正文
            BodyPart messageBodyPart = new MimeBodyPart();
            multipart.addBodyPart(messageBodyPart);
            messageBodyPart.setContent(text, "text/html;charset=utf-8");

            // 创建附件
            if (file != null && StringUtils.isNotBlank(fileName)) {
                BodyPart attachmentBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(file);
                attachmentBodyPart.setDataHandler(new DataHandler(source));
                attachmentBodyPart.setFileName(MimeUtility.encodeText(fileName));
                multipart.addBodyPart(attachmentBodyPart);
            }

            // 发送
            message.saveChanges();
            trans = session.getTransport();
            trans.connect();
            trans.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            log.error("邮件发送不可用,请联系管理员!", e);
            throw e;
        } catch (Exception e) {
            log.error("邮件发送失败", e);
            throw new DataTunnelWebException(e.getMessage(), e);
        } finally {
            if (trans != null) {
                try {
                    trans.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        MailConfigModel model = new MailConfigModel();
//        model.setEmail("mailtest@test.com");
//        model.setHost("test.com");
//        model.setUsername("mailtest@test.com");
//        model.setPort(25);
//        model.setPassword("123456");
//        model.setProtocol("smtp");
        sendMail(model, "Test", "This is a test email", "");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值