邮件工具类

package com.itheima.utils;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 邮件工具类
 *
 * @date 2022/03/14 16:39
 **/
public class SMSUtil {

    /**
     * 创建简单的文本邮件
     *
     * @param session     session对象
     * @param mailFrom    邮件发送方地址
     * @param mailTo      邮件接收方地址
     * @param mailTittle  邮件标题
     * @param mailContent 邮件内容
     * @return MimeMessage
     */
    public static MimeMessage simpleMail(Session session, String mailFrom, String mailTo, String mailTittle, String mailContent) {
        //创建默认的MimeMessage 对象
        MimeMessage msg = new MimeMessage(session);
        try {
            //邮件发送人
            msg.setFrom(mailFrom);
            //邮件接收人
            msg.setRecipients(Message.RecipientType.TO, mailTo);
            //邮件标题头
            msg.setSubject(mailTittle);
            //邮件发送日期
            msg.setSentDate(new Date());
            //邮件文本内容
            msg.setContent(mailContent, "text/html;charset=UTF-8");
        } catch (Exception mex) {
            mex.printStackTrace();
        }
        return msg;
    }

    /**
     * 创建带有附件的邮件
     *
     * @param session     session对象
     * @param contentMap  邮件配置和邮件内容
     * @param attachments 邮件附件
     * @return MimeMessage
     */
    public static MimeMessage attachMail(Session session, Map<String, Object> contentMap, List<File> attachments) {
        // 创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            //邮件发送人
            mimeMessage.setFrom(contentMap.get("mailFrom").toString());
            //邮件接收人
            mimeMessage.setRecipients(Message.RecipientType.TO, contentMap.get("mailTo").toString());
            //邮件主题
            mimeMessage.setSubject(contentMap.get("mailTittle").toString());
            //创建多重消息
            MimeMultipart multipart = new MimeMultipart();
            //邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(contentMap.get("mailContent").toString(), "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);
            //邮件附件
            if (attachments != null) {
                for (File attachment : attachments) {
                    BodyPart attachmentPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(attachment);
                    attachmentPart.setDataHandler(new DataHandler(source));
                    //避免中文乱码的处理
                    attachmentPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
                    multipart.addBodyPart(attachmentPart);
                }
            }
            mimeMessage.setContent(multipart, "UTF-8");
            //保存邮件
            mimeMessage.saveChanges();
        } catch (Exception mex) {
            mex.printStackTrace();
        }
        return mimeMessage;
    }

    /**
     * 发送邮件方法
     *
     * @param contentMap 邮件配置和邮件内容map
     */
    public static void sendEmail(Map<String, Object> contentMap) {
        sendEmail(contentMap, null);
    }

    /**
     * 发送邮件方法
     *
     * @param contentMap 邮件配置和邮件内容map
     * @param attaches   邮件配置带附件
     */
    public static void sendEmail(Map<String, Object> contentMap, List<File> attaches) {
        try {
            //获取系统属性
            Properties pros = new Properties();
            pros.setProperty("mail.transport.protocol", "smtp");// 使用的协议
            pros.setProperty("mail.smtp.host", contentMap.get("host").toString());// 发件人的邮箱的SMTP服务器地址
            pros.setProperty("mail.smtp.auth", "true");// 需要请求认证
            //设置邮件服务器
            Session session = Session.getInstance(pros);
            if (attaches == null) {
                //发送简单的文本邮件
                MimeMessage msg = simpleMail(session, contentMap.get("mailFrom").toString(), contentMap.get("mailTo").toString(), contentMap.get("mailTittle").toString(), contentMap.get("mailContent").toString());
                Transport.send(msg, contentMap.get("mailFrom").toString(), contentMap.get("passwd").toString());
                System.out.println("Sent simpleMail successfully...");
            } else {
                //发送带附件邮件
                MimeMessage mimeMessage = attachMail(session, contentMap, attaches);
                Transport.send(mimeMessage, contentMap.get("mailFrom").toString(), contentMap.get("passwd").toString());
                System.out.println("Sent attaches Email successfully...");
            }
        } catch (Exception mex) {
            mex.printStackTrace();
        }
    }

}

测试用例

import com.itheima.utils.SMSUtil;
import com.itheima.utils.ValidateCodeUtils;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class sendMessage {
    @Test
    public void sendMessagea() {
        Map map = new HashMap<>();
        //发件人地址
        map.put("mailFrom","316*****@qq.com");
        //收件人地址
        map.put("mailTo","16******4@163.com");
        //发件人邮件服务器地址
        map.put("host","smtp.qq.com");
        //邮件标题
        map.put("mailTittle","测试用例");
        //邮件正文
        map.put("mailContent", ValidateCodeUtils.generateValidateCode4String(6));
        map.put("passwd","av*******l**aj");
        SMSUtil.sendEmail(map);
    }
}

posted @ 2022-11-10 02:19  ajajaz  阅读(18)  评论(0编辑  收藏  举报