其他分享
首页 > 其他分享> > springboot发送163邮件通知

springboot发送163邮件通知

作者:互联网

准备:

  1. 需要一个163邮箱账号,没有自己去注册

  2.PC端登录如下图操作:

    

==============================================================================

代码实现

  1.创建Springboot项目

  2.引入依赖 pom.xml

        <!--springboot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--springboot test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

  3.配置文件 application.properties

  # 应用服务 WEB 访问端口
   server.port=8080
  #email相关配置
   spring.mail.host=smtp.163.com
   spring.mail.username=XXX@163.com   登录的用户名
   spring.mail.password=XXXXX         授权码
   spring.mail.default-encoding=utf-8
   spring.mail.properties.mail.smtp.auth=true
   spring.mail.properties.mail.smtp.starttls=true
   spring.mail.properties.mail.smtp.starttls.enable=true
   spring.mail.properties.mail.smtp.starttls.required=true

  4.创建实体类 Email

public class Email{
    /**
     * 接受邮箱账户
     */private String mail;

    /**
     * 邮箱标题
     */private String title;

    /**
     * 要发送的内容
     */private String content;


    /**
     * get/set方法
     */

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

  5.创建控制层  Controller

@Controller
public class MailService {
    @Autowired
    private MailSender mailSender;
   
   //获取配置文件中的自己邮箱 @Value("${spring.mail.username}") private String sendUserName; //发送消息 @RequestMapping("send") public void send(@RequestBody Email email) { System.out.println("进入发送"); System.out.println(sendUserName); System.out.println(email.getMail() + "==" + email.getTitle() + "==" + email.getContent());      //new 消息对象 SimpleMailMessage message = new SimpleMailMessage(); //发件人邮箱 message.setFrom(sendUserName); //收件人邮箱 message.setTo(email.getMail()); //标题 message.setSubject(email.getTitle()); //正文 message.setText(email.getContent()); //发送 mailSender.send(message); } }

  6.启动服务,使用postman 或者 Apifox 调用接口

    postman:

              

 

 

    Apifox:

    

 

 

   7.查看邮箱

    

 

 

 

 

  

   

标签:String,spring,email,mail,message,163,public,邮件,springboot
来源: https://www.cnblogs.com/Life-QX/p/16392830.html