目标:springboot,使用异步方式后台发送邮件。
关键点:异步服务不能在同类里调用。
1、mail依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
2、yml配置
spring:
mail:
host: smtp.126.com
port: 25
username: abc99@126.com
password: HXAABBCCBEJLSYPQ
properties:
mail:
debug: false
username:发件人邮件地址,
password:发件人邮箱密码或者授权码
3、代码实现
3.1 线程池准备
@Configuration @EnableAsync public class ThreadPoolConfig { @Bean("messageThread") public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 设置核心线程数 executor.setCorePoolSize(4); // 设置最大线程数 executor.setMaxPoolSize(8); // 设置队列容量 executor.setQueueCapacity(100); // 设置线程活跃时间(秒) executor.setKeepAliveSeconds(60); // 设置默认线程名称 executor.setThreadNamePrefix("com.wood.message-"); // 设置拒绝策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任务结束后再关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(60); return executor; } }
3.2 邮件服务
@Slf4j @Service public class MailServiceImpl implements MailService { @Resource private JavaMailSender javaMailSender; @Value("${spring.mail.username}") private String sender; @Override @Async("messageThread") //对应线程池的bean,使用线程池实现异步调用 public void sendMail(List<SysUser> receivers, String subject, String content) {
// 获取收件人邮件地址数组 String[] receiverMails = receivers.stream().map(SysUser::getEmail).filter(StringUtils::isNotBlank).distinct().toArray(String[]::new); if(receiverMails.length<1) return; SimpleMailMessage message = new SimpleMailMessage();
// 邮件主题 message.setSubject(subject);
// 发件人 message.setFrom("邮件提醒<"+sender+">");
// 收件人数组 message.setTo(receiverMails);
// 发送日期 message.setSentDate(new Date());
// 正文 message.setText(content); javaMailSender.send(message); log.info("邮件提醒,收件人:"+ Arrays.toString(receiverMails)+",内容:"+content); } }