SpringBoot简单邮件发送
pom文件里加入spring-boot-starter-mail依赖
<!--SpringBoot邮件服务-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties里加入配置,这边使用163邮箱http://www.zeromemos.com/index/article/read.html?id=232
spring.mail.host=smtp.163.com
spring.mail.username=zjcnhs123@163.com
spring.mail.password=XXXXX
spring.mail.default-encoding=UTF-8
# 启动ssl
spring.mail.properties.mail.smtp.ssl.enable=true
# 启动tls
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000
创建邮件服务接口MailService和实现类MailServiceImpl
package com.zeromemos.service;
public interface MailService {
void sendSimpleMail(String to, String subject, String content);
}
package com.zeromemos.service.impl;
import com.zeromemos.service.MailService;
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;
@Service
public class MailServiceImpl implements MailService {
@Autowired
JavaMailSender javaMailSender;
@Value("${spring.mail.username}") //直接从配置文件获取username的值
private String from;
@Override
public void sendSimpleMail(String to, String subject, String content) {
// 简单邮件可以直接构建一个SimpleMailMessage对象进行配置,配置完成后,通过JavaMailSender将邮件发送出去。
SimpleMailMessage simpMsg = new SimpleMailMessage();
simpMsg.setFrom(from);//发送者
simpMsg.setTo(to);//收件者
//simpMsg.setCc(cc);//抄送人
simpMsg.setSubject(subject);//主题
simpMsg.setText(content);//内容
javaMailSender.send(simpMsg);
}
}
到控制器里加入测试代码
@Autowired
private MailService mailService;
@GetMapping("/send/{to}")
public R send(@PathVariable String to){
String subject = "邮件主题:XXX";
String content = "邮件内容:XXX";
mailService.sendSimpleMail(to, subject, content);
return R.ok();
}
访问http://localhost:8001/send/xxxx@qq.com,后面跟你的测试接收邮箱
接收成功