java基于freemarker发送邮件,模板邮件,图片邮件

发布时间:2019-05-20
技术:springboot2+freemarker+mail

概述

基于freemarker发送模板邮件,图片邮件,文本邮件等。基于ftl模板,邮件样式美观。

详细

一、前言

FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。【百度百科】

二、效果预览

微信截图_20190517172233.png

三、程序实现

1、项目结构图

1558086620946042896.png

2、相关参数配置

spring:
  mail:
    #设置邮箱主机
    host: smtp.ym.163.com
    #设置用户名
    username: lnbld@bld365.com
    #这里不是注册时的密码,而是生成的授权码
    password: "bld123456"
    port: 465
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          #设置是否需要认证,如果为true,那么用户名和密码就必须的
          auth: true
          starttls:
            #加密通讯,true开启,false不开启
            enable: true
            #是否必须通过使用加密通讯进行通讯,true开启,false不开启
            required: true
          socketFactory:
            port: 465
            class: javax.net.ssl.SSLSocketFactory
            fallback: false

3、测试类

package com.sylujia.mail;

import com.sylujia.mail.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    @Autowired
    private MailService mailService;

    @Test
    public void sendTemplateMailTest(){
        Map<String, Object> mailContentMap = new HashMap<>();
        mailContentMap.put("contactName", "sylujia");
        mailContentMap.put("platformAddr", "https://www.baidu.com");
        mailContentMap.put("loginName", "sylujia");
        mailContentMap.put("loginPswd", "123456");
        mailContentMap.put("payPswd", "123456");
        mailContentMap.put("contactMail", "xxx@163.com");
        mailContentMap.put("contactPhone", "13144112255");
        try {
            mailService.sendTemplateMail("系统账号开通", "xxx@163.com","AccountOpenMail.ftl", mailContentMap);
        } catch (Exception e) {
            log.error("账号开通邮件发送失败:{}", mailContentMap , e);
        }
        log.info("邮件发送成功");
    }



}

4、邮件服务

package com.sylujia.mail.service.impl;

import com.sylujia.mail.service.MailService;
import freemarker.template.Configuration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.internet.MimeMessage;
import java.util.Map;

@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public boolean sendTemplateMail(String title, String toUser, String templateName, Map<String, Object> params) {
        try {

            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            // 发件人
            helper.setFrom(from);
            //收件人
            helper.setTo(toUser);
            //邮件标题
            helper.setSubject(title);

            Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
            configuration.setClassForTemplateLoading(this.getClass(), "/templates");
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate(templateName), params);
            //// text:内容,true:为HTML邮件(false则为普通文本邮件)
            helper.setText(text, true);
            mailSender.send(mimeMessage);

        } catch (Exception e) {
            log.error("sendTemplateMail 发送模板邮件错误,", e);
            throw new RuntimeException(e);
        }
        return true;
    }

}

四、总结

邮件发送本地(Windows环境)能测试成功,部署到linux服务器后一直报错 

com.sun.mail.util.MailConnectException: Couldn't connect to host异常解决

重要信息Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host和22。首先想到的是linux的端口22没有开通,遂联系相关人员开通,但是可能出于安全考虑没有同意开通。 

没办法,只能更换端口了,需要对配置进行修改,这里我换的465端口,具体看上面配置信息。

如果使用的是云服务器,例如阿里云、腾讯云等。需要注意,他们出于安全考虑可能会限制邮件端口,这个需要咨询,实在不行就改用465 ssl端口发送邮件。


本实例支付的费用只是购买源码的费用,如有疑问欢迎在文末留言交流,如需作者在线代码指导、定制等,在作者开启付费服务后,可以点击“购买服务”进行实时联系,请知悉,谢谢
手机上随时阅读、收藏该文章 ?请扫下方二维码