(十八)SpringBoot之发送QQ邮件
一、引入maven依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
二、配置application.properties
spring.mail.host=smtp.qq.com
spring.mail.username=邮箱名
spring.mail.password=这里填邮箱的授权码
spring.mail.default-encoding=UTF-8
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
- 注意:
- PO3/SMTP服务必须开启
2.QQ邮箱发送邮件服务器主机名为:smtp.qq.com,必须使用使用SSL(spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory),端口号465或587(spring.mail.port=465)
3. 发送邮件
package com.shyroke.controller; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/mail") public class MailController { @Autowired JavaMailSender mailSender; @ResponseBody @RequestMapping("/send") public Object sendEmail() { try { final MimeMessage mimeMessage = this.mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setFrom("qweyhj@qq.com"); message.setTo("865386512@qq.com"); message.setSubject("测试邮件主题"); message.setText("测试邮件内容"); this.mailSender.send(mimeMessage); return "sucesss"; } catch (Exception ex) { ex.printStackTrace(); return "error"; } } }
4. 结果