1.在pom.xml放入一下代码↓↓
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.在application.properties配置mail
#qq邮箱 只使用了qq邮箱
spring.mail.host=smtp.qq.com
#想要发送邮箱的一方
spring.mail.username=12580007@qq.com
#开启pop3/smtp服务后的授权码 登录自己的qq邮箱点设置账户往下划就可以看见了
spring.mail.password=fdhgurtowakxjijds
spring.mail.default-encoding=UTF-8
#想要发送邮箱的一方
mail.fromMail.addr=12580007@qq.com
3.编写MailService 类
@Component
public class MailService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
@Value("${mail.fromMail.addr}")
private String from;
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
mailSender.send(message);
logger.info("简单邮件已经发送。");
} catch (Exception e) {
logger.error("发送简单邮件时发生异常!", e);
}
}
}
4.编写测试类在src/test/java目录下 使用测试要引入spring-boot-starter-test
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private MailService mailService;
// @Autowired
// private TemplateEngine templateEngine;
@Test
public void testSimpleMail() throws Exception {
mailService.sendSimpleMail("10068321@qq.com","邮件测试"," 愿你更好!!");
}
}
到此就结束了
这个测试类你可以从页面获取 从controller获取数据在调用mailService.sendSimpleMail