1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > SpringBoot实现qq邮箱发送邮件

SpringBoot实现qq邮箱发送邮件

时间:2023-01-30 16:56:10

相关推荐

SpringBoot实现qq邮箱发送邮件

SpringBoot实现qq邮箱发送邮件

一、导入springboot提供的依赖二、在配置文件中设置邮箱信息设置邮箱三、设置邮件内容等四、设置发送邮箱为单独的线程操作

一、导入springboot提供的依赖

<!--发送邮箱依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>

二、在配置文件中设置邮箱信息

设置邮箱

spring.mail.host=spring.mail.port=465spring.mail.protocol=smtp# 发送邮箱的账号spring.mail.username=XXXXX@# 此为开通qq邮箱POP3/SMTP服务之后的激活码spring.mail.password=********spring.mail.default-encoding=UTF-8spring.mail.test-connection=true# 可以不用设置spring.mail.properties.mail.smtp.socketFactory.class=.ssl.SSLSocketFactoryspring.mail.properties.mail.smtp.debug=true

三、设置邮件内容等

@Componentpublic class RegisterEmailService {@Value("${spring.mail.username}")private String fromEmail;@Autowiredprivate JavaMailSender javaMailSender;@Asyncpublic void sendEmail(String toEmail){// 验证真的使用我们自己线程System.out.println(Thread.currentThread().getName());SimpleMailMessage message = new SimpleMailMessage();// 设置发件人账号message.setFrom(fromEmail);// 设置收件人账号message.setTo(toEmail);// 设置邮件标题message.setSubject("【Lyman】注册激活邮件");// 设置邮件内容String content = "您的注册已成功,请点击链接去激活";message.setText(content);javaMailSender.send(message);}}

@Async:开启异步,为springboot提供的注解,我们可以重写它的线程池

四、设置发送邮箱为单独的线程操作

@EnableAsync@Configuration(proxyBeanMethods = false)public class EmailThreadPool implements AsyncConfigurer {//处理线程执行过程中异常(记录日志:保存现场)@Overridepublic AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {return AsyncConfigurer.super.getAsyncUncaughtExceptionHandler();}private static final int CORE_POOL_SIZE = 2;private static final int MAX_POOL_SIZE = 5;private static final int KEEP_ALIVE_SECONDS = 10;/*** 设置前缀*/private static final String THREAD_NAME_PREFIX = "email-thread-";/*** 如果不设置队列上限,造成系统崩溃*/private static final int QUEUE_CAPACITY = 1000;/*** 自定义线程池* @return*/@Overridepublic Executor getAsyncExecutor() {// 使用 spring 提供的线程池 定制操作ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();// 1.设置核心线程数executor.setCorePoolSize(CORE_POOL_SIZE);// 2.设置最大线程数executor.setMaxPoolSize(MAX_POOL_SIZE);// 3.设置空闲线程存活时间executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);// 5. 设置线程工厂 (使用是JUC 线程工具类Executors 提供线程工厂 )executor.setThreadFactory(new CustomizableThreadFactory(THREAD_NAME_PREFIX));// 6. 线程任务队列要使用有界(有限的)队列executor.setQueueCapacity(QUEUE_CAPACITY);// 7. 等待当前线程池中线程任务完成才去关闭(必须设置)executor.setWaitForTasksToCompleteOnShutdown(true);// 8. 采用juc中 ThreadPoolExecutor 直接丢弃executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());executor.initialize();return executor;}}

@EnableAsync:开启异步

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。