记录一下基于spring boot实现自动发送邮箱的功能。
1. 导入依赖
2. 邮箱设置和配置文件设置
(1)邮箱设置
(a)开启服务;
(b)设置授权码,点击新增按钮即可;
(c)复制服务地址到项目的配置文件中,我这里用的是smtp.163.com
(2)配置文件设置
# 利用163个人邮箱发送邮件
mail.fromMail.addr=******@163.com
spring.mail.host=smtp.163.com
spring.mail.password=******
spring.mail.properties.smtp.auth=true
spring.mail.properties.smtp.timeout=25000
spring.mail.username=******@163.com
3.代码编写
(1)编写Service类接口
public interface MailService {
/**
*
* @param to 收件人的邮箱
* @param subject 邮件标题
* @param content 邮件内容
*/
void sendMail(String to,String subject,String content);
}
(2)接口的实现
@Service
public class MailServiceImplimplements MailService {
@Autowired
private JavaMailSenderjavaMailSender;
@Value("${mail.fromMail.addr}")
private Stringfrom;
@Override
public void sendMail(String to, String subject, String content) {
SimpleMailMessage mailMessage=new SimpleMailMessage();
mailMessage.setFrom(from);//邮件发送者
mailMessage.setTo(to);//邮件接受者
//mailMessage.setTo("to1.com","to2.com","to3.com");//实现多人发送
mailMessage.setSubject(subject);
mailMessage.setText(content);
try {
javaMailSender.send(mailMessage);
System.out.println("发送邮件");
}catch (Exception e){
System.out.println("发送失败");
e.printStackTrace();
}
}
}
(3)测试类中进行测试
@Test
public void testSendMail(){
try{
//设置你想要将邮件发送到哪个邮箱
String to ="******@qq.com";
//后面两个参数,设置邮件的主题、邮件的文本内容
mailServiceImpl.sendMail(to, "这个是邮件标题", "这里是邮件的具体内容,具体的内容由我们自己控制!");
System.out.println("ok");
}catch (Exception ex){
ex.printStackTrace();
}
}
4.测试结果