开启QQ邮箱POP3/SMTP服务
添加Maven依赖
<!-- 邮件发送 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置application.properties
spring.mail.password为邮箱的十六位授权码,不是邮箱的登录密码。
#-----------------------------------------Spring Boot 邮件发送---------------
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=XXX@qq.com
spring.mail.password=aaaabbbbccccdddd
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
邮件发送服务
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class MailService {
// JavaMailSender是Spring Boot在MailSenderPropertiesConfiguration类中配置好的,该类在Mail自动配置类MailSenderAutoConfiguration中导入
@Autowired
JavaMailSender javaMailSender;
/**
*
* @param from 邮件发送者
* @param to 收件人
* @param cc 抄送人
* @param subject 邮件主题
* @param content 邮件内容
*/
public void sendSimpleMail(String from, String to, String cc, String subject, String content) {
SimpleMailMessage simpMsg = new SimpleMailMessage();
simpMsg.setFrom(from);
simpMsg.setTo(to);
simpMsg.setCc(cc);
simpMsg.setSubject(subject);
simpMsg.setText(content);
javaMailSender.send(simpMsg);
}
}
发送邮件测试
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sang.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SendmailApplicationTests {
@Autowired
MailService mailService;
@Test
public void sendSimpleMail() {
mailService.sendSimpleMail("from@qq.com",
"to@qq.com",
"cc@qq.com",
"测试邮件主题",
"测试邮件内容");
}
}
异常处理
org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535 Error: ÇëʹÓÃÊÚȨÂëµÇ¼¡£ÏêÇéÇë¿
- 没有配置spring.mail.password
- spring.mail.password填写成登录密码而不是授权码
- 十六位授权码填写在配置文件中时,它们之间不应该有空格