Java +Freemarker实现发送邮件

jar

       <!--Email相关开始-->
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <!--Email相关结束-->

Mail邮件对象

public class Mail implements Serializable {
    private static final long serialVersionUID = 1L;
    //接收方邮件
    private String email;
    //主题
    private String subject;
    //模板
    private String template;
    // 自定义参数
    private Map<String, Object> params;
    }

实现

@Component
public class MailSendService {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

   //发件人
    @Value("${spring.mail.username}")
    private String fromMail;
   //主题名称
    //@Value("${mail.subjectName}")
    //private String subjectName;
    /**
     * 根据模板名 获取邮件内容
     */
   private String getMailTextByTemplateName(String templateName, Map<String, Object> params) throws IOException, TemplateException {
        try {
            String mailText = "";
            //通过指定模板名获取FreeMarker模板实例
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
            mailText = FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
            return mailText;
        }catch (TemplateNotFoundException e) {
        //若找不到指定模板则使用默认模板
                templateName="busi_situation.ftl";
                Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
                return FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
        }
    }
    public Result sendWithHTMLTemplate(Mail mail) {
        try {
            String email = mail.getEmail();
            if (StringUtil.isBlank(email)) {
                return ResultUtil.error("邮箱email不能为空!");
            }
            if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
                return ResultUtil.error("邮箱email格式不正确!");
            }
            //发件人昵称
            String nick = MimeUtility.encodeText(fromMail);
            //发件人
            InternetAddress from = new InternetAddress(nick + "<" + fromMail + ">");
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //收件人
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setFrom(from);
            //图片
            String fileUrl = this.getClass().getClassLoader().getResource("public/static/img/mail/logo.png").getPath();
            FileSystemResource img1 = new FileSystemResource(new File(fileUrl));
            mimeMessageHelper.addInline("logo1", img1);
            FileSystemResource img2 = new FileSystemResource(new File(fileUrl));
            mimeMessageHelper.addInline("logo2", img2);
            
           //附件
   	   String filePath= this.getClass().getClassLoader().getResource("public/static/img/mail/text.txt").getPath();
      	   FileSystemResource file=new FileSystemResource(new File(filePath));
           String fileName=filePath.substring(filePath.lastIndexOf(File.separator));
      	   //添加多个附件可以使用多条
     	   mimeMessageHelper.addAttachment(fileName,file);

            Map<String, Object> params = mail.getParams();
            mail.setParams(params);
            mimeMessageHelper.setSubject(subjectName);
            // 使用模板生成html邮件内容
            String result = getMailTextByTemplateName(mail.getTemplate(), mail.getParams());
            mimeMessageHelper.setText(result, true);
            javaMailSender.send(mimeMessage);
            return ResultUtil.success("邮件发送成功");
        } catch (Exception e) {
            logger.error("发送邮件失败" + e.getMessage());
            return ResultUtil.error("发送邮件时发生异常:" + e.getMessage());
        }
    }

}

邮件服务器SSL安全证书认证

public class MailSocketFactory extends SSLSocketFactory {

    private SSLSocketFactory factory;

    public MailSocketFactory() {
        try {
            // 获取一个SSLContext实例
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{new MailTrustManager()}, null);
            //从上述SSLContext对象中得到SSLSocketFactory对象
            factory = sslcontext.getSocketFactory();
        } catch (Exception ex) {
            // ignore
        }
    }

    public static SocketFactory getDefault() {
        return new MailSocketFactory();
    }

    @Override
    public Socket createSocket() throws IOException {
        return factory.createSocket();
    }

    @Override
    public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException {
        return factory.createSocket(socket, s, i, flag);
    }

    @Override
    public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, int j) throws IOException {
        return factory.createSocket(inaddr, i, inaddr1, j);
    }

    @Override
    public Socket createSocket(InetAddress inaddr, int i) throws IOException {
        return factory.createSocket(inaddr, i);
    }

    @Override
    public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException {
        return factory.createSocket(s, i, inaddr, j);
    }

    @Override
    public Socket createSocket(String s, int i) throws IOException {
        return factory.createSocket(s, i);
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return factory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return factory.getSupportedCipherSuites();
    }
}

证书信任管理器

public class MailTrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }
    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }
    //返回受信任的X509证书数组。
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

配置文件

spring.mail.default-encoding=UTF-8
spring.mail.host=mail.x'x'x.x'x'x.xxx
spring.mail.username=x'x'xxxxxxx
spring.mail.password=x'x'xxxx
# 协议
spring.mail.protocol=smtp
spring.mail.port=x'x'x
spring.mail.properties.mail.smtp.auth=truexxx
spring.mail.properties.mail.smtp.starttls.enable=false
spring.mail.properties.mail.smtp.starttls.required=false
spring.mail.properties.mail.smtp.socketFactory.port=x'x'x
## SSL认证工厂
spring.mail.properties.mail.smtp.socketFactory.class=com.xxx.msg.impl.MailSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback=false

freemarrker模板

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>截至邮件发送时间</title>
    <meta http-equiv="keywords" content="data">
    <meta http-equiv="description" content="data">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>

<body >
<div class="content">
    <div class="main">
        <div class="status">
            <div class="status-top">
                <div class="logo flex-align"> <img src="cid:logo1" alt="" width="35" height="35"><span>${data.name}</span></div>
            
            <div class="status-content">
                <div class="status-content-top flex-align flex-justify-center">
                    <h2>xxx</h2>
                    <span>
                        <i></i>
                        <i></i>
                        <i></i>
                    </span>
                </div>
                <div class="status-content-c flex-r flex-jusify-space-bettween">
                    <div class="normal flex-c flex-align flex-justify-center">
                        <p>${data.sum}</p>
                        <span>xxx</span>
                    </div>
                    <div class="success flex-c flex-align flex-justify-center">
                        <p>${data.sum}</p>
                        <span>xxx</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="dataDec">
            <div>
                <h4 class="flex-align">xxx</h4>
                <table>
                    <thead>
                    <tr>
                        <th width="180"  align="left">名称</th>
                    </tr>
                    </thead>
                    <tbody>
                    <#list data as item>
                        <tr>
                            <#list item?keys as itemKey>
                                <#if itemKey="name" >
                                    <td align="left">${item[itemKey]}</td>
                                </#if> 
                            </#list>
                        </tr>
                    </#list>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>
posted @ 2020-06-22 15:35  Amy小影儿  阅读(965)  评论(0编辑  收藏  举报