一、导入依赖,开启邮箱SMTP服务,查看邮箱服务商文档
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=369
二、添加配置文件
spring: mail: host: smtp.qq.com port: 465 username: xxxxxx@foxmail.com password: xxxxxxxxx default-encoding: UTF-8 properties: mail: debug: true smtp: socketFactory: class: javax.net.ssl.SSLSocketFactory
三、编写测试类
import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; @Autowired JavaMailSender javaMailSender; @Test void mailtest1() { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); //邮件发送者 simpleMailMessage.setFrom("xxxxx@qq.com"); // 收件人 simpleMailMessage.setTo("xxxxxx@qq.com"); // 抄送人 simpleMailMessage.setCc("xxxxx@qq.com"); // 邮件主题 simpleMailMessage.setSubject("系统测试"); // 邮件内容 simpleMailMessage.setText("hi,QQ mail"); javaMailSender.send(simpleMailMessage); } @Test void mailtest2() throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); // 邮件发送者 helper.setFrom("xxxxx@qq.com"); // 收件人 helper.setTo("xxxxxx@qq.com"); // 抄送人 helper.setCc("xxxxxx@qq.com"); // 邮件主题 helper.setSubject("系统测试"); // 邮件内容 helper.setText("hi,QQ mail"); // 添加附件 helper.addAttachment("阅读总结.zip", new File("C:\\Users\\xxxxx\\Desktop\\1615355849695.zip")); javaMailSender.send(mimeMessage); }