SpringBoot发送邮件
1、pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<scope>test</scope>
</dependency>
2、yml
spring.mail.username=90xxxxx31@qq.com
spring.mail.password=qq邮箱授权码
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.mail.smtp.enable=true
3、mailSender
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.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
@SpringBootTest
class SpringbootTaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("桔梗,你好");
simpleMailMessage.setText("感谢你一生的陪伴");
simpleMailMessage.setSubject("桔梗");
simpleMailMessage.setTo("26xxxxx83@qq.com");
simpleMailMessage.setFrom("90xxxxx31@qq.com");
mailSender.send(simpleMailMessage);
}
@Test
void contextLoads2() throws MessagingException {
//一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("桔梗,你好");
helper.setText("<p style='color:red'>感谢你一生的陪伴 +" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "+</p>", true);
helper.addAttachment("美女1.jpeg", new File("C:\Users\A\Desktop\美女1.jpeg"));
helper.addAttachment("美女2.jpg", new File("C:\Users\A\Desktop\美女2.jpg"));
helper.setTo("26xxxxx83@qq.com");
helper.setFrom("90xxxxx31@qq.com");
mailSender.send(mimeMessage);
}
}