1. 开启以下服务,并获取其授权码作为客户端的登录密码
或者其他邮箱同理
2. 创建springboot项目,导入email相关的依赖
<!--导入email辅助包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3.在yml或properties配置文件配置需要的配置
#邮箱配置
mail:
protocol: smtp
host: smtp.qq.com
port: 587
username: xxxxxx@qq.com
password: xxxxxxxxx
default-encoding: utf-8
properties:
mail:
debug: true #会完整的打印邮箱的日程日志
smtp:
connectiontimeout: 5000
timeout: 3000
writetimeout: 5000
4.创建简单的邮件发送工具类或者业务层
此为业务层实例
import xxx.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service("emailService")
@Transactional(rollbackFor = Exception.class)
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
@Override
public boolean send(String emailAddress, String code) {
log.info("获取验证码中");
//定制纯文本邮件信息
SimpleMailMessage message=new SimpleMailMessage();
try {
//qq的smtp发送服务器的名称
message.setFrom(from);
//收件人的邮箱
message.setTo(emailAddress);
//要发送的邮件主题
message.setSubject("邮箱认证");
//邮件的内容
String content = emailAddress+code;
message.setText(content);
javaMailSender.send(message);
log.info("发送验证码成功");
return true;
}catch (MailSendException e){
e.printStackTrace();
return false;
}
}
}