添加依赖:
<!--邮件依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--velocity模板-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
application.properties的配置:注意,我使用的是163邮箱发送邮件,如果使用qq邮箱发送,配置会稍有不同
# JavaMailSender 邮件发送的配置
spring.mail.host=smtp.163.com
#邮件发送者
spring.mail.username=xxx@163.com
#邮件的接收者
spring.mail.tomail=xxx@qq.com
#设置的是客户端授权密码,不是邮箱的登录密码
spring.mail.password=xxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
qq邮箱发送邮件发的配置:
######qq邮箱########
spring.mail.host=smtp.qq.com
spring.mail.username=******@qq.com
#QQ邮箱授权码
spring.mail.password=xuojxtkdojvzbhjj
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
注意密码的配置,设置的是客户端授权密码,不是邮箱的登录密码,以163邮箱为例,需要保证如下的设置
登录163邮箱,修改如下的操作
需要开启如下的授权码,在properties中配置的密码就是这个开启的授权码,不能是密码
编写邮件发送类
package com.tencent.springbootsendmail.service.impl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tencent.springbootsendmail.model.ProductInfo;
import com.tencent.springbootsendmail.service.SendMailService;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.tools.generic.NumberTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.annotation.PostConstruct