需要有一个邮箱 以126邮箱为例 必选开启下图打勾项(发送者)
pom.xml的依赖
<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>
application.properties的配置
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.126.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.RestController;
@RestController
public class Mailcontroller {
@Autowired
JavaMailSender jms;
@GetMapping("/send")
public String send(){
SimpleMailMessage smm=new SimpleMailMessage();
//发送者
smm.setFrom("发送者邮箱名");
//接收者
smm.setTo("接收者邮箱名");
//标题
smm.setSubject("测试邮件");
//内容
smm.setText("hello");
jms.send(smm);
return "发送成功";
}
}
Mian(启动项)
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);
}
}