当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot实现邮件发送功能

Spring Boot实现邮件发送功能

2019年07月22日  | 移动技术网IT编程  | 我要评论

0755深圳旅游招聘,商朝国王,囚你草草鸟事

本文实例为大家分享了spring boot邮件发送功能的具体代码,供大家参考,具体内容如下

1、引入依赖

 <!-- mail依赖 -->
  <dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-mail</artifactid>
 </dependency>

2、参数配置

在application.properties中配置邮件相关的参数

spring.thymeleaf.cache=false

spring.mail.host=smtp.qq.com
spring.mail.username=***@qq.com
spring.mail.password=ymwrdffauajebgde //此处的密码时qq邮箱的授权码
spring.mail.properties.mail.smtp.auth=true 
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.stattls.required=true

3、邮件service代码

@service
public class mailservice {

  @value("${spring.mail.username}")
  private string from;
  
  @autowired
  private javamailsender sender;
  
  /*发送邮件的方法*/
  public void sendsimple(string to, string title, string content){
    simplemailmessage message = new simplemailmessage();
    message.setfrom(from); //发送者
    message.setto(to); //接受者
    message.setsubject(title); //发送标题
    message.settext(content); //发送内容
    sender.send(message);
    
    system.out.println("邮件发送成功");
    
  }
}

4、编写页面代码

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" 
   xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="utf-8" />
<title>insert title here</title>
</head>
<body>
  <h1 th:inlines="text">邮件发送</h1>
  <form action="sendmail" method="post">
    <p>选择文件: <input type="text" name="title"/></p>
    <p><input type="submit" value="提交"/></p>
  </form>
</body>
</html>

5、邮件请求处理

@controller
public class mailcontroller {

  @autowired
  private mailservice mailservice;
  
  private string to="***@qq.com";
  
  @requestmapping("mail")
  public string mail(){
    return "/mail";
  }
  
  @requestmapping("sendmail")
  @responsebody
  public string sendmail(@requestparam("title")string title){
    system.out.println("-----title: " + title);
    mailservice.sendsimple(to, title, title);
    return "success";
  }
}

6、测试

7、qq邮箱授权码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网