springboot + freemarker + javamail整合

首先进入springboot guide reference,你就可以看到以下这么一段内容:

36. Sending Email
The Spring Framework provides an easy abstraction for sending email by using the JavaMailSender interface, and Spring Boot provides auto-configuration for it as well as a starter module.
Tip
See the reference documentation for a detailed explanation of how you can use JavaMailSender.
If spring.mail.host and the relevant libraries (as defined by spring-boot-starter-mail) are available, a default JavaMailSender is created if none exists. The sender can be further customized by configuration items from the spring.mail namespace. See MailProperties for more details.
In particular, certain default timeout values are infinite, and you may want to change that to avoid having a thread blocked by an unresponsive mail server, as shown in the following example:
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000

就可以得知pom.xml引入:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

因为本文还需要整合freemarker,因此需要引入:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

引入工作完成,接下来就是如何写了,查看自动配置源码:

/*

 * Copyright 2012-2018 the original author or authors.

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



package org.springframework.boot.autoconfigure.mail;



import java.nio.charset.Charset;

import java.nio.charset.StandardCharsets;

import java.util.HashMap;

import java.util.Map;



import org.springframework.boot.context.properties.ConfigurationProperties;



/**

 * Configuration properties for email support.

 *

 * @author Oliver Gierke

 * @author Stephane Nicoll

 * @author Eddú Meléndez

 * @since 1.2.0

 */

@ConfigurationProperties(prefix = "spring.mail")

public class MailProperties {



	private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;



	/**

	 * SMTP server host. For instance, `smtp.example.com`.

	 */

	private String host;



	/**

	 * SMTP server port.

	 */

	private Integer port;



	/**

	 * Login user of the SMTP server.

	 */

	private String username;



	/**

	 * Login password of the SMTP server.

	 */

	private String password;



	/**

	 * Protocol used by the SMTP server.

	 */

	private String protocol = "smtp";



	/**

	 * Default MimeMessage encoding.

	 */

	private Charset defaultEncoding = DEFAULT_CHARSET;



	/**

	 * Additional JavaMail Session properties.

	 */

	private Map<String, String> properties = new HashMap<>();



	/**

	 * Session JNDI name. When set, takes precedence over other Session settings.

	 */

	private String jndiName;



	public String getHost() {

		return this.host;

	}



	public void setHost(String host) {

		this.host = host;

	}



	public Integer getPort() {

		return this.port;

	}



	public void setPort(Integer port) {

		this.port = port;

	}



	public String getUsername() {

		return this.username;

	}



	public void setUsername(String username) {

		this.username = username;

	}



	public String getPassword() {

		return this.password;

	}



	public void setPassword(String password) {

		this.password = password;

	}



	public String getProtocol() {

		return this.protocol;

	}



	public void setProtocol(String protocol) {

		this.protocol = protocol;

	}



	public Charset getDefaultEncoding() {

		return this.defaultEncoding;

	}



	public void setDefaultEncoding(Charset defaultEncoding) {

		this.defaultEncoding = defaultEncoding;

	}



	public Map<String, String> getProperties() {

		return this.properties;

	}



	public void setJndiName(String jndiName) {

		this.jndiName = jndiName;

	}



	public String getJndiName() {

		return this.jndiName;

	}



}

源码指明了以spring.mail为前缀的配置说明,按要求进行如下application.yml配置:

spring:
  mail:
    host: smtp.example.com
    username: 你的邮箱
    password: 授权码or密码
    properties.mail.smtp:
      auth: true
      starttls.enable: true
      starttls.required: true
    port: 25

freemarker的yml配置如下:

spring:
  freemarker:
    suffix: .ftl
    allow-request-override: false
    cache: true
    check-template-location: true
    charset: utf-8
    content-type: text/html
    expose-request-attributes: false
    expose-session-attributes: false
    expose-spring-macro-helpers: false
    template-loader-path:
          - classpath:/templates
  mvc:
        static-path-pattern: /static/**

接下来就是最关键的代码如何写了,先简单来一段代码,我直接写上了模板类,一般都能囊括一般普通类型了。

定义一个MailUtil类:

package com.My.Util;

import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.xml.crypto.dsig.TransformService;
import javax.xml.transform.Templates;
import java.util.HashMap;
import java.util.Map;

@Component
public class MailUtil {

    @Autowired
    private FreeMarkerConfigurer fmc;

    @Autowired
    private JavaMailSender javaMailSender;

    public boolean sendMail(String email, String header, String name){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

            mimeMessageHelper.setSubject(header);
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setFrom("[email protected]");//这个必须加,不加就报错。当然和你设置的username是一样的。


            Template t =  fmc.getConfiguration().getTemplate("hello_world.ftl");//获取模板

            Map<String, Object> map = new HashMap<>();
            map.put("name", name);

            String content = FreeMarkerTemplateUtils.processTemplateIntoString(t, map);//解析模板

            mimeMessageHelper.setText(content, true);

            javaMailSender.send(mimeMessage);
            return true;

        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}

其他简单的springboot基本内容就不写了,其他简单类型,度娘也搜到,本文主要是对springboot进行一个整合总结。

猜你喜欢

转载自blog.csdn.net/u012117299/article/details/80562142