首先:导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.yml里面配置
mail:
username: 。。。。@qq.com # 发送人邮箱
password: klxrnmvozgv # 邮箱授权码(上面获取到的)
host: smtp.qq.com # 邮件服务器,163邮箱就是smtp.163.com
protocol: smtp # 协议,可以不配,默认就是这个
发送邮件的方法,sevrice
package com.zjtx.email.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
/**
* 邮件发送工具类
*
* @author wuxiaobing
* @date 2022年10月21日13:10
*/
@Component
public class EmailUtils {
// 发送邮件服务
@Autowired
private JavaMailSender javaMailSender;
// 发送者
@Value("${spring.mail.username}")
private String from;
/**
* 发送简单文本邮件
* @param subject 主题
* @param content 内容
* @param to 收件人列表
* @author BillDowney
* @date 2022年10月21日13:35
*/
public void sendSimpleMail(String subject, String content, String... to) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setSubject(subject);
message.setText(content);
message.setTo(to);
javaMailSender.send(message);
}
}
controller类
package com.zjtx.email.controller;
import com.zjtx.email.utils.EmailUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* @author wuxiaobing
* @date 2022年10月21日14:12
* @description:
*/
@RestController
@RequestMapping("email")
public class EmailTestController {
@Resource
private EmailUtils emailUtils;
@GetMapping("/sendMailTest")
public String sendMailTest() {
emailUtils.sendSimpleMail("测试邮件发送", "这是一封测试邮件的内容.......", "xxx@126.com");
return "mail send success";
}
}