IntelliJ IDEA 2017版 spring-boot 2.0.5 邮件发送简单实例 (三)

时间:2023-01-19 00:46:46

一、搭建SpringBoot项目

详见此文:https://www.cnblogs.com/liuyangfirst/p/8298588.html

注意:

需要添加mail依赖的包,同时还添加了lombock,方便日志打印。如图所示

IntelliJ IDEA 2017版 spring-boot 2.0.5 邮件发送简单实例 (三)IntelliJ IDEA 2017版 spring-boot 2.0.5 邮件发送简单实例 (三)

IntelliJ IDEA 2017版 spring-boot 2.0.5 邮件发送简单实例 (三)

二、启动Application,测试项目搭建是否成功

IntelliJ IDEA 2017版 spring-boot 2.0.5 邮件发送简单实例 (三)

三、配置properties文档

 #########邮箱协议
spring.mail.host=smtp.163.com ####还可以是smtp.126.com 等
##########发送邮件的用户名
spring.mail.username= 你的邮箱
########移动端客户授权码(需要开通POP3授权)
spring.mail.password= 授权密码
#######配置邮件发送默认编码utf-8
spring.mail.default-encoding=UTF-8

注意:
        需要授权码,163为例,163官网授权码开通如下

https://help.mail.163.com/faqDetail.do?code=d7a5dc8471cd0c0e8b4b8f4f8e49998b374173cfe9171305fa1ce630d7f67ac2cda80145a1742516

四、业务逻辑

1、需要发件人邮箱地址

2、需要调用自带邮箱封装的类,JavaMailSender

3、需要将收件人,主题,内容填入到方法内,最后,调用JavaMailSender的send方法发送

 package com.baidu.mailtest.service;

 import lombok.extern.slf4j.Slf4j;
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; /******************************
* @author : liuyang
* <p>ProjectName:mail </p>
* @ClassName : MailService
* @date : 2018/9/22 0022
* @time : 22:57
* @createTime 2018-09-22 22:57
* @version : 2.0
* @description :
*
*
*
*******************************/ @Service
@Slf4j
public class MailService { /**
* 发件人邮箱地址
*/
@Value("${spring.mail.username}")
private String fromUserName; @Autowired
private JavaMailSender javaMailSender; /**
* 一般发送邮件方法
*
* @param to 发送给某人
* @param subject 邮件主题
* @param context 邮件内容
*/
public void sendSimpleMail(String to, String subject, String context) { SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(context);
simpleMailMessage.setFrom(fromUserName); javaMailSender.send(simpleMailMessage);
} }

五、编写测试类

 package com.baidu.mailtest;

 import com.baidu.mailtest.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; @RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class MailServiceApplicationTests { @Resource
MailService mailService; @Test
public void sayMail() { mailService.sendSimpleMail("收件人邮箱", "SpringBoot邮件测试", "今天需要很多美女陪我"); log.info("发送成功");
} }

六、观察测试结果

注意发送时候,测试类比较慢,如图位置会卡一会儿。

IntelliJ IDEA 2017版 spring-boot 2.0.5 邮件发送简单实例 (三)

发送成功如图:

IntelliJ IDEA 2017版 spring-boot 2.0.5 邮件发送简单实例 (三)

七、源码分享

git@github.com:liushaoye/mailtest.git