学习记录
1、安装项目依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、配置application.properties
spring.mail.host=smtp.qq.com
spring.mail.username=发送方qq@qq.com
spring.mail.password=授权码
spring.mail.properties.mail.smtp.port=465
spring.mail.from=发送方qq@qq.com
3、SendEmailServer .java 发送邮件的业务层
package com.example.iot_kcsj.server;
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.Service;
import javax.annotation.Resource;
/**
* 发送邮件业务层
* */
@Service
public class SendEmailServer {
// 这里需要注意,一开始我用的是@Autowired注解,但是不能注入JavaMailSender,具体原因我也不太清楚
@Resource
JavaMailSender javaMailSender;
/**
* 配置文件中我的qq邮箱
*/
@Value("${spring.mail.from}")
private String from;
public void sendSimpleMail(String to, String subject, String content) {
//创建SimpleMailMessage对象
SimpleMailMessage message = new SimpleMailMessage();
//邮件发送人
message.setFrom("2038834512@qq.com");
//邮件接收人
message.setTo(to);
//邮件主题
message.setSubject(subject);
//邮件内容
message.setText(content);
//发送邮件
javaMailSender.send(message);
}
}
4、SendEmailController.java 发送邮件控制层
package com.example.iot_kcsj.controller;
import com.example.iot_kcsj.server.SendEmailServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 发送邮件控制层
* */
@RestController
public class SendEmailController {
@Autowired
SendEmailServer mailService;
@GetMapping("/send_email")
public void sendEmail(){
mailService.sendSimpleMail("发送方qq@qq.com","主题:你好普通邮件","内容:第一封邮件");
}
}
5、目录结构