一、开启POP3/SMTP服务
二、配置pom.xml
<!-- 邮件依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
三、配置application.yml
# JavaMailSender 邮件发送的配置 spring: mail: host: smtp.qq.com username: 12345678@qq.com # 授权码 password: aaaaaaaaaaaaaaaa properties: mail: smtp: auth: true starttls: enable: true required: true
四、编写工具类
@Component public class MyEmailUtil { @Autowired private JavaMailSender javaMailSender; public void sendEmail(String sendTo, String title, String content, File file) { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom("12345678@qq.com"); mimeMessageHelper.setTo(sendTo); mimeMessageHelper.setSubject(title); mimeMessageHelper.setText(content); if (file.exists()) { FileSystemResource fileSystemResource = new FileSystemResource(file); mimeMessageHelper.addAttachment(file.getName(), fileSystemResource); } } catch (MessagingException e) { e.printStackTrace(); } javaMailSender.send(mimeMessage); } }