开场白:没记错的话,用不同框架开发一个发邮箱的功能,都会遇到多多少少的问题,这次也不能例外,否则就没有意义了。
今天用springboot2.0.4开发发邮件功能,遇到了以下三个坑
- 项目中添加了该依赖,但是仍旧找不到
下面的对象,一直说该对象没有被发现,后来发现是少了包
@Autowired
private JavaMailSender mailSender;
pom.xml中引入这两个
<!--虽然我发现依赖里面有了这个包,但是愣是不好使,非得让我dependency一遍,被这个问题坑了半个小时-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- 调用发邮件的功能 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2 写发送的类。
package com.loy.spring;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailApplicationServiceTest {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String fromMail;
@Test
public void sendSimpleMail() throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromMail); // 必须要和上文配置的spring.mail.username内容相同
message.setTo("wangxy11@yusys.com.cn");
message.setSubject("主题:测试邮件");
message.setText("测试邮件内容");
System.out.println(fromMail);
mailSender.send(message);
}
注意上面的 @Value("${spring.mail.username}") 是从配置文件中找的。
也就是需要再resources文件夹下增加 properties文件,一般为
application.properties文件,我是用qq发送邮箱,内容如下:
#email
spring.mail.host=smtp.qq.com
spring.mail.username=1439537@qq.com
spring.mail.password=uposqxqbtxzwighg
spring.mail.properties.mail.smtp.ssl.trust=smtp.qq.com
#SSL\u8BC1\u4E66Socket\u5DE5\u5382
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
#\u4F7F\u7528SMTPS\u534F\u8BAE465\u7AEF\u53E3
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.password=uposqxqbtxzwighg
注意:这个密码是qq开启SMTP服务的授权码,并不是你的真正的qq的密码哦。按照这个配置粘贴过去就行了哦。
- 简单来说 1 引入依赖 2 配置properties 3登陆qq邮箱获取授权码加入到properties中 3就是写Test类,用JunitTest测试即可发送邮件。
这就是Spring-boot调用邮箱发邮件的问题,对了,qq邮箱不能设置独立密码,否则邮件发不出去后,会报连接不上smtp.qq.com这个错误,切记。
======================================================
结束语:不积跬步无以至千里,不积小流无以成江海
V:1861237242 欢迎java学习交流。