添加依赖
<!-- 邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.yml配置
#邮件发送
spring:
mail:
host: smtp.qq.com
username: 438562332@qq.com
password: #此处填写授权码,不是密码
protocol: smtp #发送邮件协议
properties.mail.smtp.auth: true
properties.mail.smtp.port: 465 #端口号465或587或25
properties.mail.display.sendmail: Javen #可以任意
properties.mail.display.sendname: Spring Boot Guide Email #可以任意
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
default-encoding: utf-8 #默认就是UTF-8,不用配置
from: xx@qq.com #与上面的username保持一致,发送人
发送邮件的类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.mail.internet.MimeMessage;
@Component
public class SendMail {
@Autowired
private JavaMailSender jmsi;
/**
* 发送邮件 - 异步发送
* 使用@Async注解,需要在启动类加上@EnableAsync注解才能生效
* @param to - 传入收件人数组
* @param str - 传入消息体,也可使html拼接的字符串
*/
@Async
public void sendMail(String [] to,String str){
try {
MimeMessage message = jmsi.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, false);//false即为不携带附件
helper.setTo(to);
helper.setFrom("438562332@qq.com");//发件人
helper.setSubject("主题");//邮件标题
helper.setText(str, true);//true代表没有附件
jmsi.send(message);//发送
System.out.println("发送完毕!!!");
}catch (Exception e){
e.printStackTrace();
}
}
}