一. 我们需要导入发送邮件 的依赖jar包
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>cn.et</groupId>
- <artifactId>SPRINGBOOT-SENDMAIL</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.9.RELEASE</version>
- </parent>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-mail</artifactId>
- </dependency>
- </dependencies>
- </project>
- spring.mail.default-encoding=UTF-8
- spring.mail.host=smtp.163.com
- spring.mail.password=密码 授权码
- spring.mail.port=25
- spring.mail.protocol=smtp
- spring.mail.username=用户名
三. 创建一个controller 发送邮件的业务
- package cn.et;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.mail.SimpleMailMessage;
- import org.springframework.mail.javamail.JavaMailSender;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- public class MailController {
- @Autowired
- private JavaMailSender jms;
- <strong><span style="color:#cc0000;">@GetMapping("/send")</span></strong>
- public String send(){
- SimpleMailMessage mailMessage = new SimpleMailMessage();
- //谁发的
- mailMessage.setFrom("*******@163.com");
- //发给谁
- mailMessage.setTo("********@qq.com");
- //标题
- mailMessage.setSubject("我");
- //内容
- mailMessage.setText("逗你玩");
- jms.send(mailMessage);
- return "1";
- }
- }
四. 创建一个启动类 启动项目
- package cn.et;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- @SpringBootApplication
- public class Main {
- public static void main(String[] args) {
- SpringApplication.run(Main.class, args);
- }
- }
五. 在浏览器中访问 地址 http://localhost:8080/send 返回 "1" 说明发送成功