建项目
改pom,导入相关依赖
org.springframework.boot
spring-boot-starter-parent
2.2.2.RELEASE
<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
/**
@author QiuQiu&LL
@create 2021-08-09 2:18
*/
@ComponentScan("com.qbb")
public class EmailSignupApplication {
public static void main(String[] args) {
SpringApplication.run(EmailSignupApplication.class, args);
}
}
业务
/**
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
*/
public class MailServiceImpl implements MailService {
@Value("${spring.mail.username}")
private String from;
private JavaMailSender mailSender;
Logger logger = LoggerFactory.getLogger(this.getClass());
/**
发送邮件
@param to 邮件收件人
@param subject 邮件主题
@param verifyCode 邮件验证码
*/
public void sendVertifyCode(String to, String subject, String verifyCode) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); //发送人
message.setTo(to); //收件人
message.setSubject(subject); //邮件名
message.setText(verifyCode); //邮件内容(验证码)
mailSender.send(message);
logger.info("已经发送");
}
}
测试
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
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EmailSignupApplication.class)
public class MailServiceTest {
private MailService mailService;
public void Test1() {
/填你的测试信息/
String to = "收件人邮箱";
String title = "测试邮件";
String context = "测试验证码";
mailService.sendVertifyCode(to, title, context);
}
}
结果
手机扫一扫
移动阅读更方便
你可能感兴趣的文章