<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> 复制代码
spring.mail.username=1550213743@qq.com spring.mail.password=******** spring.mail.host=smtp.qq.com #开启加密验证 spring.mail.properties.mail.smtp.ssl.enable=true 复制代码
4.EmailApplicationTests类里进行测试, contextLoads为简单的发送,仅限于文本。contextLoads2为复杂,可以发送图片,html格式
package com.xyj; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @SpringBootTest class EmailApplicationTests { @Autowired JavaMailSenderImpl mailSender; @Test void contextLoads() { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setSubject("你好"); mailMessage.setText("123456"); mailMessage.setTo("1550213743@qq.com"); mailMessage.setFrom("1550213743@qq.com"); mailSender.send(mailMessage); } @Test void contextLoads2() throws MessagingException { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true); helper.setSubject("你好"); helper.setText("<p style='color:red'>这是红色的</p>",true); helper.addAttachment("bg.jpg",new File("D://money//网页//疫情//images//bg1.jpg")); helper.setTo("1550213743@qq.com"); helper.setFrom("1550213743@qq.com"); mailSender.send(mimeMessage); } } 复制代码