导入依赖

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

配置

application.properties

# 需要开启 smtp qq邮箱为例
spring.mail.host=smtp.qq.com
spring.mail.port=465
# 发件人的邮箱
spring.mail.username=xxxxx
# qq 邮箱的第三方授权码 并非个人密码
spring.mail.password=xxxx
#开启ssl 否则 503 错误
spring.mail.properties.mail.smtp.ssl.enable=true

service

package com.it.whitejotterapi.service;
import com.it.whitejotterapi.tools.JsonResult;
/**
* @Author: 羡羡
* @Date: 2022/05/29/10:28
*/
public interface SendEmail {
/**
* 发送email邮件
* @param to 接收人的邮箱
* @param subject 主题
* @param content 内容
* @return
*/
JsonResult sendmessage(String to,String subject,String content);
}

service

package com.it.whitejotterapi.service;
import com.it.whitejotterapi.tools.JsonResult;
/**
* @Author: 羡羡
* @Date: 2022/05/29/10:28
*/
public interface SendEmail {
/**
* 发送email邮件
* @param to 接收人的邮箱
* @param subject 主题
* @param content 内容
* @return
*/
JsonResult sendmessage(String to,String subject,String content);
}

serviceimpl

package com.it.whitejotterapi.service.impl;
import com.it.whitejotterapi.service.SendEmail;
import com.it.whitejotterapi.tools.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @Author: 羡羡
* @Date: 2022/05/29/10:36
*/
@Service
public class SendEmailServiceImpl implements SendEmail {
@Resource
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
/**
* 发送邮件
* @param to 接收人的邮箱
* @param subject 主题
* @param content 内容
* @return
*/
@Override
public JsonResult sendmessage(String to, String subject, String content) {
try {
SimpleMailMessage message = new SimpleMailMessage();
//发件人
message.setFrom(from);
//收件人
message.setTo(to);
//邮件主题
message.setSubject(subject);
//邮件内容
message.setText(content);
//发送邮件
javaMailSender.send(message);
return new JsonResult(200,"发送成功!");
}catch (Exception e){
return new JsonResult(500,"发送失败!");
}
}
}

控制器

package com.it.whitejotterapi.controller;
import com.it.whitejotterapi.service.impl.SendEmailServiceImpl;
import com.it.whitejotterapi.service.impl.SendMessageImpl;
import com.it.whitejotterapi.tools.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: 羡羡
* @Date: 2022/05/29/10:49
*/
@RestController
public class SendEmailContoller {
@Autowired
SendEmailServiceImpl seim;
/**
* 发送邮件
* @param to 收邮件的人
* @param subject 主题
* @param context 内容
* @return
*/
@RequestMapping(path = "/send",method = RequestMethod.POST)
public JsonResult send(String to,String subject,String context){
return seim.sendmessage(to,subject,context);
}
}