pom.xml 依赖
<!-- mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties配置
以下是邮件相关配置,其他java服务配置请自行解决
#...
#发送相关邮件配置
spring.mail.host=smtp.qq.com
#发送方的邮箱(必填)
spring.mail.username=自己的@qq.com
#对于qq邮箱而言 密码指的就是发送方的授权码(必填)百度查如何获取授权码即可
spring.mail.password=填写自己的(lopfxqasfadadehg)
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
#端口号,不设置默认为25,而端口号25现已被很多云服务商禁用,如果非要用25,需申请解封,这里使用端口号:465
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false
#...
MailController
这里是学习java的一个小demo,仅做为笔记
package com.testOne.controller;
import com.testOne.common.BaseResult;
import com.testOne.common.SuccessResult;
import com.testOne.model.User;
import com.testOne.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
/**
* @author ...
* @date Created in 15:28 2021/6/8
* @description
* 邮箱发送实现类
*/
@RestController
@Slf4j
@RequestMapping(value = "/mail", produces = "application/json")
public class MailController {
@Autowired
private MailSender mailSender;
@Autowired
private UserService userService;
// 发送人邮箱
private final String MAIL_FROM = "自己的@qq.com";
@RequestMapping(value="/sendMails",method = RequestMethod.GET )
@ApiOperation(value = "发送邮件", notes ="通过id查询用户信息表中维护的邮件地址" )
public BaseResult send (@ApiParam(value="用户id",required = true) @RequestParam("id") String id) throws Exception {
String setSubject = "重置密码";
User user = userService.getUserById(id);
// new 一个简单邮件消息对象
SimpleMailMessage message = new SimpleMailMessage();
// 和配置文件中的的username相同,相当于发送方
message.setFrom(MAIL_FROM);
// 收件人邮箱
message.setTo(user.getEmail());
// 标题
message.setSubject(setSubject);
// 正文
message.setText("<html>" +
"<body>" +
"恭喜你密码重置成功" +
"</body>" +
"</html>");
// 发送
try{
mailSender.send(message);
log.info("主题"+setSubject+"邮件接收人"+user.getEmail());
}catch (Exception e){
log.error("主题"+setSubject+"邮件接收人"+user.getEmail()+"邮件发送出现异常");
log.error("异常信息为"+e.getMessage());
log.error("-------------");
e.printStackTrace();
throw new Exception("EMAIL_SERVE_EXCEPTION");
}
return new SuccessResult("重置密码信息已发送到您的邮箱");
}
}