建项目
改pom,导入相关依赖
spring-boot-starter-parent
<dependencies> <!--web依赖--> <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> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
写Yml,配置application.yml
server:
port: 端口号
spring:
mail:
#邮件发送配置
default-encoding: UTF-8
host: smtp.qq.com
# 授权码
password: 你的授权码
# 邮件发送安全配置
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
# 发件人信息
username: 发件人邮箱
主启动类EmailSignupApplication
/**
业务
/**
package com.qbb.email_signup.service.impl;
import com.qbb.email_signup.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
/**
@author QiuQiu&LL
@create 2021-08-09 2:20
@Description:
*/
@Service
public class MailServiceImpl implements MailService {
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
Logger logger = LoggerFactory.getLogger(this.getClass());
/**
测试
package com.qbb.email_signup;
import com.qbb.email_signup.service.MailService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
@author QiuQiu&LL
@create 2021-08-09 2:28
@Description:
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EmailSignupApplication.class)
public class MailServiceTest {
@Autowired
private MailService mailService;
@Test
public void Test1() {
/填你的测试信息/
String to = "收件人邮箱";
String title = "测试邮件";
String context = "测试验证码";
mailService.sendVertifyCode(to, title, context);
}
}
结果