今天学习了springboot整合了JavaMail。
首先导入坐标:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
接下来做配置,本人用的是yml文件:
spring: mail: host: smtp.qq.com # smtp:smtp协议,qq:邮件供应商 username: 105465468@qq.com //本人qq邮箱 password: afklmasklfnkl //非qq邮箱的登录密码,而是服务器给你提供的一个加密的密码
接下来发送邮件:
//发送邮件接口
public interface SendMailService { void sendMail() throws MessagingException; }
//发送邮件接口实现类
@Service public class SendMailServicelmpl implements SendMailService { @Autowired //注入发送客户端 private JavaMailSender javaMailSender; //发送人,邮箱地址 private String from = ""; //接收人,邮箱地址 private String to = ""; //标题 private String subject = "测试邮件"; //正文 private String context = "测试邮件正文内容"; @Override public void sendMail() { //发送简单邮件 SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from + "(小明)"); //"(小明)"替代发送人信息 message.setTo(to); message.setSubject(subject); message.setText(context); javaMailSender.send(message); } }
@SpringBootTest //springboot测试类 class Springboot22MailApplicationTests { @Autowired //自定义功能,发送邮件 private SendMailService service; @Test void contextLoads() throws MessagingException { service.sendMail(); } }
欢迎大家一起学习,有不足的地方还请指出。