一、完成配置
在完成Spring Boot模板的基础上,完成配置
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.neo</groupId>
<artifactId>helloWorld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>helloWorld</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
spring.mail.host=smtp.126.com
spring.mail.username=你的126邮箱
spring.mail.password=126授权码
spring.mail.default-encoding=utf-8
二、完成编写MailService类
编写MailService
package com.neo.helloWorld.hello;
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;
@Service
public class MailService {
@Value("${spring.mail.username}")
private String form;
@Autowired
private JavaMailSender mailSender;
public void sayHello(){
System.out.println("Hello World!");
}
public void sendSimpleMail(String to,String subject,String content){
SimpleMailMessage message=new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
message.setFrom(form);
mailSender.send(message);
}
}
三、完成测试类
package com.neo.helloWorld.service;
import com.neo.helloWorld.hello.MailService;
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
public class ServiceTest {
@Resource
MailService mailService;
@Test
public void sayHelloTest(){
mailService.sayHello();
}
@Test
public void sendSimpleMailTest(){
mailService.sendSimpleMail("ifyouknowi@126.com","这是第一封邮件","大家好,这是我的第一封邮件!");
}
}
完成效果:
可能出现的问题及改正方法: