准备工作
1、 登陆QQ邮箱,设置-账户-POP3/SMTP服务(开启,开启成功会返回一个密码)
注:记住开启成功的密码,配置时需要。
开始
1、在pom.xml中加载maven资源
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、在 application.properties 中配置参数
spring.mail.host=smtp.qq.com
spring.mail.prot=587
spring.mail.username= // 你的邮箱
spring.mail.password= // 刚才开启时的密钥
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactoryCalss=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debig=true
3、创建发送邮件工具类 EmailTool.java
public class EmailTool {@Autowiredprivate JavaMailSender javaMailSender;// 单发public void sendOneEmail(String fromEmail,String toEmail,String title,String context){SimpleMailMessage message = new SimpleMailMessage();message.setSubject(title);// 从哪里 发送message.setFrom(fromEmail);// 到哪里 可设置多个,实现群发message.setTo(toEmail);message.setSentDate(new Date());message.setText(context);try {javaMailSender.send(message);log.info("邮件发送成功");} catch (Exception e){e.printStackTrace();log.error("邮件发送失败");}}// 发送附件public void sendFileEmail(String fromEmail,String toEmail,String title,String context,String fileName,String filePath) throws MessagingException {MimeMessage mimeMessage = javaMailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);helper.setSubject(title);helper.setFrom(fromEmail);helper.setTo(toEmail);helper.setSentDate(new Date());helper.setText(context);helper.addAttachment(fileName,new File(filePath));javaMailSender.send(mimeMessage);}
}
4、测试。