SpringBoot 异步发送邮件
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、测试发送邮件
spring.mail.username=*****@163.com
spring.mail.password=*****
spring.mail.host=smtp.163.com
package com.ybs;
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.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SpringSyncApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void sendMail1() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("Springboot 测试邮件");
mailMessage.setText("Springboot实现发送邮件");
mailMessage.setTo("****@163.com");
mailMessage.setFrom("****@163.com");
mailSender.send(mailMessage);
}
@Test
void sendMail2() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("Springboot 测试复杂邮件");
helper.setText("<p style='color:blue'>Springboot实现发送复杂邮件</p>", true);
helper.addAttachment("1.png", new File("D:\\Users\\ybsde\\IdeaProjects\\SpringBoot\\spring-sync\\src\\main\\resources\\1.png"));
helper.addAttachment("1.png", new File("D:\\Users\\ybsde\\IdeaProjects\\SpringBoot\\spring-sync\\src\\main\\resources\\1.png"));
helper.setTo("****@163.com");
helper.setFrom("****@163.com");
mailSender.send(mimeMessage);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d7143b16488a51a5df93afd212eb21bc.png)
@Service
public class ScheduleService {
// 在一个特定的时间执行这个方法
// cron 表达式
// 秒 分 时 日 月 周几
// 30 0/5 10,18 * * ? 每天10点和18点,每5分钟执行一次
@Scheduled(cron = "0/5 * * * * 0-7")
public void hello(){
System.out.println("hello, 你被执行了~");
}
}