基于Spring封装的Javamail实现邮件发送

1.依赖

<dependency>
	<groupId>org.springframeworkgroupId>
	<artifactId>spring-context-supportartifactId>
	<version>4.1.5.RELEASEversion>
dependency>

<dependency>
    <groupId>javax.mailgroupId>
    <artifactId>mailartifactId>
    <version>1.4.7version>
dependency>


<dependency>
    <groupId>org.freemarkergroupId>
    <artifactId>freemarkerartifactId>
    <version>2.3.23version>
dependency>

2.配置

#启用邮件通知
mail.enabled=true
#服务器主机名
mail.smtp.host=mail.163.com
#邮件服务端口(不填就是用默认端口),smtp默认端口为25
mail.smtp.port=587
#邮箱地址
mail.smtp.username=xxxx
#你的授权码,有些邮箱服务器使用密码就可以了
mail.smtp.password=xxxxx
#编码格式
mail.smtp.defaultEncoding=UTF-8
#是否进行用户名密码校验
mail.smtp.auth=true
#发送邮件日志级别
mail.smtp.debug=true

3.参数封装类



import java.util.List;
import java.util.Properties;

/**
 * 发送邮件参数
 * @author Created by niugang on 2019/10/15/9:54
 */
public class MailSendParameters {
    /**
     * 接收者
     */
    private List<String> receivers;
    /**
     * 会议主题
     */
    private String subject;

    /**
     * 会议描述
     */
    private String description;

    /**
     * 会议时间
     */
    private String time;

    /**
     * 会议地点
     */
    private String address;


    /**
     * 发送者姓名
     */
    private String senderName;





    public List<String> getReceivers() {
        return receivers;
    }

    public void setReceivers(List<String> receivers) {
        this.receivers = receivers;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getSenderName() {
        return senderName;
    }

    public void setSenderName(String senderName) {
        this.senderName = senderName;
    }


}

4.核心发送工具类

/**
 * @author Created by niugang on 2019/10/14/16:54
 */

public class MailSendUtil {

    private static final Logger logger = LoggerFactory.getLogger(MailSendUtil.class);

    private static final String BOOLEAN_REGEX = "^false$|^true$";

    private static final String MAIL_CONF_PATH = "/home/xdja/conf/meeting/mail.properties";

    private static final Pattern PATTERN = Pattern.compile(BOOLEAN_REGEX);


    private static Properties mailProperties;

    /**
     * 判断邮件功能是否开启,默认邮件功能为关闭的
     * true 开启
     * false 关闭
     *
     * @return boolean
     */
    public static boolean isMailEnabled() {
        readPropertiesFile();
        String mailEnabled = mailProperties.getProperty("mail.enabled");
        if (StringUtils.isNotBlank(mailEnabled)) {
            String mailEnabledLowerCase = mailEnabled.toLowerCase();
            Matcher matcher = PATTERN.matcher(mailEnabledLowerCase);
            if (!matcher.matches()) {
                throw new IllegalArgumentException("mail.enabled parameter format error,parameter true or false, case ignored");
            }
            boolean aBoolean = Boolean.parseBoolean(mailEnabled);
            if (!aBoolean) {
                logger.info("mail.enabled is false ,no need to send email");
            }
            return aBoolean;
        }
        return false;
    }


    /**
     * 读取配置文件
     */
    private static void readPropertiesFile() {
        try {
            mailProperties = readProperties();
        } catch (FileNotFoundException e) {
            logger.error("Properties file not found");
        }
        if (mailProperties == null) {
            throw new NullPointerException("Properties file must not be null");
        }



    }


    /**
     * 发送邮件
     */
    public static void sendMail(final MailSendParameters mailSendParameters) {
        if (mailProperties == null) {
            readPropertiesFile();
        }
        List<String> receivers = mailSendParameters.getReceivers();
        if (receivers.isEmpty()) {
            throw new NullPointerException("Mail receiver must not be null");
        }
        if (mailSendParameters.getSubject() == null) {
            throw new NullPointerException("Mail subject must not be null");
        }

        try {
            String[] receiversArray = mailSendParameters.getReceivers().toArray(new String[0]);
            JavaMailSender javaMailSender = getJavaMailSender(mailProperties);
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //发送者 必须和配置的 mail.smtp.username 一样
            mimeMessageHelper.setFrom(mailProperties.getProperty("mail.smtp.username"));
            //接收者
            mimeMessageHelper.setTo(receiversArray);
            //邮件主题
            mimeMessageHelper.setSubject(mailSendParameters.getSubject());
            //邮件内容
            mimeMessageHelper.setText(getText(mailSendParameters), true);

            javaMailSender.send(mimeMessage);
            logger.info("Meeting [mail] send success...");
        } catch (Exception e) {
            logger.info("Meeting [mail] send failed...",e);
        }

    }





    /**
     * 创建发送对象
     *
     * @return JavaMailSender
     */
    private static JavaMailSender getJavaMailSender(Properties paramProp) {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(paramProp.getProperty("mail.smtp.host"));
        javaMailSender.setUsername(paramProp.getProperty("mail.smtp.username"));
        javaMailSender.setPassword(paramProp.getProperty("mail.smtp.password"));
        String portStr = paramProp.getProperty("mail.smtp.port");
        if (StringUtils.isNotBlank(portStr)) {
            javaMailSender.setPort(Integer.parseInt(portStr));
        }
        String defaultEncoding = paramProp.getProperty("mail.smtp.defaultEncoding");
        if (StringUtils.isNotBlank(defaultEncoding)) {
            javaMailSender.setDefaultEncoding(defaultEncoding);
        }
        String auth = paramProp.getProperty("mail.smtp.auth");
        String debug = paramProp.getProperty("mail.smtp.debug");
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth", StringUtils.isNotBlank(auth) ? auth : "true");
        properties.setProperty("mail.debug", StringUtils.isNotBlank(debug) ? debug : "true");
        javaMailSender.setJavaMailProperties(properties);
        return javaMailSender;
    }

    /**
     * 读取freemarker模板的方法
     */
    private static String getText(MailSendParameters mailSendParameters) {
        String txt = "";
        try {
            //freemarker包
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
            //设置模板加载文件夹
            configuration.setDirectoryForTemplateLoading(new File(ResourceUtils.getURL("classpath:").getPath() + "template"));
            Template template = configuration.getTemplate("mail.ftl");

            // 通过map传递动态数据
            Map<String, Object> map = new HashMap<>();
            map.put("subject", mailSendParameters.getSubject());
            map.put("time", mailSendParameters.getTime());
            map.put("address", mailSendParameters.getAddress());
            map.put("sponsor", mailSendParameters.getSenderName());
            map.put("description", mailSendParameters.getDescription());
            // 解析模板文件
            txt = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        } catch (Exception e) {
            logger.error("Create send [mail] template exception:{}", e);
            throw new ServiceException("Create send [mail] template exception");
        }

        return txt;
    }


 
    /**
     * 读取发送邮件配置,实时读取,为了修改配置不重启服务
* * 或者使用WatchService 启动线程对文件状态进行监控
* * https://blog.csdn.net/niugang0920/article/details/102594552 * * @return Properties * @throws FileNotFoundException FileNotFoundException */
private static Properties readProperties() throws FileNotFoundException { Properties properties = new Properties(); File file = new File(MAIL_CONF_PATH); if (!file.exists()) { logger.error(MAIL_CONF_PATH + "is not exist"); throw new FileNotFoundException(MAIL_CONF_PATH + "is not exist"); } FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); properties.load(fileInputStream); } catch (IOException e) { logger.error("Read [mail] properties failed:{}", e); } finally { try { if (fileInputStream != null) { fileInputStream.close(); } } catch (IOException e) { logger.error("Close FileInputStream failed:{}", e); } } return properties; } }

5.发送模板

在src/resources下新建template文件夹

添加mail.ftl模板

<table width="700" border="1" cellspacing="0" cellpadding="0">
    <tr>
        <td style="text-align: center">
            会议主题:
        td>
        <td style="font-weight: bold;text-align: center">
            ${subject!""}
        td>
    tr>
    <tr>
        <td style="text-align: center" width="100">
            会议时间:
        td>
        <td style="font-weight: bold;text-align: center">
            ${time!""}
        td>
    tr>
    <tr>
        <td style="text-align: center">
            会议地点:
        td>
        <td style="font-weight: bold;text-align: center">
            ${address!""}
        td>
    tr>

    <tr>
        <td style="text-align: center">
            会议主持人/组织者:
        td>
        <td style="text-align: center">
            ${sponsor!""}
        td>
    tr>

    <tr>
        <td style="text-align: center">
            会议描述:
        td>
        <td style="text-align: center">
            ${description!""}
        td>
    tr>

    <tr>
        <td style="text-align: center">
            与会人员:
        td>
        <td style="text-align: center">
            如收件人
        td>
    tr>

table>

6.调用测试

在controller中进行调用测试,以下为调试代码

  MailSendParameters mailSendParameters = new MailSendParameters();
            mailSendParameters.setAddress("4号会议室");
            mailSendParameters.setDescription("学习经验分享");
            mailSendParameters.setSubject("分布式微服务技术分享交流会");
            mailSendParameters.setReceivers(new ArrayList<String>() {
                                                {   ////收件人邮箱
                                                    add("xxxxxxx");
                                                }

                                            }
            );
            mailSendParameters.setSenderName("张三");
            mailSendParameters.setTime("2019年10月15日星期二 19:00-20:00");
            if(MailSendUtil.isMailEnabled()){
                MailSendUtil.sendMail(mailSendParameters);
            }

7.效果

微信公众号

基于Spring封装的Javamail实现邮件发送_第1张图片
JAVA程序猿成长之路
分享资源,记录程序猿成长点滴。专注于Java,Spring,SpringBoot,SpringCloud,分布式,微服务。

你可能感兴趣的:(spring)