1.QQ邮箱开启服务 获取授权码
2.在配置文件进行相关配置
spring:
mail:
host: smtp.qq.com
port: 587
username: xxx
password: xxx
default-encoding: utf-8
properties:
mail:
smtp:
connectiontimeout: 5000
timeout: 3000
writetimeout: 5000
3.读取配置类
/**
* 读取yml配置文件里面的信息
*/
@Configuration
@ConfigurationProperties(prefix = "spring.mail")
@Data
public class MailConfig {
private String username;
}
4.emalDto类
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class EmailDto {
/**
* 接收邮箱
*/
private String toEmali;
/**
* 主题
*/
private String subject;
/**
* 内容
*/
private String content;
}
5.在service里面添加接口
public interface EmailService {
/**
* 发送邮件
*
* @param emailDto 邮箱列表
*/
boolean send(EmailDto emailDto);
}
6.实现Service
@Slf4j
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {
@Autowired
private MailConfig mailConfig;
@Resource
private JavaMailSenderImpl mailSender;
@Override
public boolean send(EmailDto emailDto) {
String fromEmail = mailConfig.getUsername();
//定制纯文本邮件信息SimpleMailMessage
SimpleMailMessage message = new SimpleMailMessage();
try {
//设置发件箱
message.setFrom(fromEmail);
//设置收件箱
message.setTo(emailDto.getToEmali());
//设置邮件主题
message.setSubject(emailDto.getSubject());
//设置邮件内容
message.setText(emailDto.getContent());
//调用Java封装好的发送方法
mailSender.send(message);
return true;
} catch (Exception e) {
System.out.println("邮件发送失败,原因:" + e.getMessage());
return false;
}
}
}
7.测试
public void send(){
EmailDto emailDto = new EmailDto();
emailDto.setToEmali("xxx@qq.com");
emailDto.setSubject("验证码");
emailDto.setContent("145615");
emailService.send(emailDto);
}