思路:


  1. 引入email启动器
  2. 配置邮件发送功能
  3. 书写发送邮件方法类,并注入自动实例化的邮件发送器
  4. 根据基本内容构造邮件消息队形,并利用邮件发送器发送邮件
  5. 开发发送邮件api

实现:

1、修改pom.xml 引入邮件自动化配置启动器

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、修改application*.properties文件,加入邮件配置

spring.mail.host=smtp.examaple.net  ## smtp服务器地址
spring.mail.username=username@examaple.net ## 发送用户的邮箱
spring.mail.password=密码 ## 发送用户的邮箱的密码,或者授权码(如163邮箱)

※ 只要导入启动器,并配置了spring.mail.host 后,邮件发送功能就已经可以使用,此时​​JavaMailSender​ 已经被springboot实例化,可以在您的程序中注入使用

3、编写写发送器业务逻辑

package club.isource.platform.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

import club.isource.platform.service.inf.MailService;

@Service
public class MailServiceImpl implements MailService {

private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

@Autowired
private JavaMailSender javaMailSender;

@Value("${spring.mail.username}")
private String fromMail;

@Override
public int sendMail(String addr, String content) {
logger.info("向地址"+addr+"发送邮件!");
try {
SimpleMailMessage msg = new SimpleMailMessage();
// 发送目的地
msg.setTo(addr);
// 发送内容
msg.setText(content);
// 发送者
msg.setFrom(fromMail);
javaMailSender.send(msg);
return 1;
} catch (Exception e) {
logger.error("发送失败:" + e.getCause());
return 0;
}

}

}

4、编写restful 接口开方此功能

此略(就是简单的调用上面的发送服务)