赞
踩
实现思路
1.使用Freemaker生成邮箱模版
2.发送邮箱为异步发送,使用SpringBoot的线程池
点击开启
根据要求发送短信
发送完毕点击我已发送,会生成授权码,!!!记住授权码
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-mail</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-freemarker</artifactId>
- <version>2.4.2</version>
- </dependency>
!!!Freemaker用于生成邮箱模版
在resources目录下创建模版文件register_email.ftl
register_email.ftl内容
${email}和${verifyCode}为需要替换的参数
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>注册验证码</title>
- </head>
- <body>
- <div>
- <div>${email},你好!</div>
- <br/>
- <div>  您好,您的验证码为: <span style="color:blue;font-size: 20px;font-weight: 700;">${verifyCode}</span>
- 验证码10分钟内有效,请在时限内完成注册。
- 期待您的加入!</div>
- <br/>
- <div>XXX有限公司</div>
- <br/>
- <div>谢谢!</div>
- </div>
- </body>
- </html>
- spring:
- mail:
- # 配置 SMTP 服务器地址
- host: mail.qq.net
- # 发送者邮箱
- username: xxxxx@qq.com
- # 配置密码,注意不是真正的密码,而是刚刚申请到的授权码
- password: xxxxxxxxxxxxx
- # 端口号465或587
- port: 465
- #默认的邮件编码为UTF-8
- default-encoding: UTF-8
- protocol: smtps
创建EmailUtils.java文件
- package com.lnsk.common.utils;
-
- import com.lnsk.common.constant.Constants;
- import freemarker.cache.ClassTemplateLoader;
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- import freemarker.template.TemplateException;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.mail.javamail.JavaMailSenderImpl;
- import org.springframework.mail.javamail.MimeMessageHelper;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.stereotype.Component;
-
- import javax.mail.MessagingException;
- import javax.mail.internet.MimeMessage;
- import java.io.IOException;
- import java.io.StringWriter;
- import java.nio.charset.Charset;
- import java.util.Date;
- import java.util.Map;
- import java.util.Properties;
-
- /**
- * 邮箱工具类
- * @author haiven
- *
- */
- @Slf4j
- @Component
- public class EmailUtils {
-
- //发件人邮箱
- @Value("${spring.mail.username}")
- private String username;
-
- //发件人密码
- @Value("${spring.mail.password}")
- private String password;
-
- //发件人host
- @Value("${spring.mail.host}")
- private String host;
-
- //发件人端口
- @Value("${spring.mail.port}")
- private String port;
-
- //邮件模板名
- private static final String TEMP_FILE_NAME = "register_email.ftl";
-
- /**
- * 发送邮件
- * @param subject 邮件主题
- * @param content 邮内容
- * @param to 邮件接收人
- * @throws MessagingException
- */
- @Async("verifyThreadPool")
- public void sendEmail(String subject,String content,String to) throws MessagingException {
- JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
- javaMailSender.setPort(port);
- javaMailSender.setUsername(username);
- javaMailSender.setPassword(password);
- javaMailSender.setHost(host);
- javaMailSender.setDefaultEncoding(Constants.UTF8);
- Properties properties = new Properties();
- properties.setProperty("mail.smtp.socketFactory.port", port);
- properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
- javaMailSender.setJavaMailProperties(properties);
- MimeMessage mailMessage=javaMailSender.createMimeMessage();
- //需要借助Helper类
- MimeMessageHelper helper=new MimeMessageHelper(mailMessage);
- log.debug("Register send email:" + username );
- helper.setFrom(username);
- helper.setTo(to);
- //helper.setBcc("密送人");
- helper.setSubject(subject);
- helper.setSentDate(new Date());//发送时间
- //第一个参数要发送的内容,第二个参数是不是Html格式。
- helper.setText(content,true);
- javaMailSender.send(mailMessage);
- }
-
- /**
- * 加载邮件模板
- * @param email & verifyCode 邮件模板参数
- * @return
- * @throws IOException
- * @throws TemplateException
- */
- public static String loadEmailContent(String email,String verifyCode) throws IOException, TemplateException {
- Map<String,String> dataMap = new HashMap<>();
- dataMap.put("email",email);
- dataMap.put("verifyCode",verifyCode);
- //初始化模板
- Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
- configuration.setDefaultEncoding(Charset.forName("UTF-8").name());
-
- //设置模板文件路径
- configuration.setTemplateLoader(new ClassTemplateLoader(EmailUtils.class,"/templates/"));
-
- //获取模板
- Template template = configuration.getTemplate(TEMP_FILE_NAME);
-
- //输出位置 这里用字符串输出,如果要输出文件自行替换
- StringWriter writer = new StringWriter();
- template.process(dataMap, writer);
- StringBuffer buffer = writer.getBuffer();
- return buffer.toString();
- }
-
- }
loadEmailContent方法为加载邮箱内容方法,参数为register_email.ftl中的email和verifyCode两个参数
创建测试类,测试发送邮箱
- package com.lnsk.order.controller;
-
- import com.lnsk.common.utils.EmailUtils;
- import freemarker.template.TemplateException;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.RestController;
-
- import javax.mail.MessagingException;
- import java.io.IOException;
-
- @RestController
- public class TestUtils {
-
- @Autowired
- EmailUtils emailUtils;
-
- //邮件主题
- private static final String SUBJECT = "测试邮箱";
-
- @GetMapping("/getVerifyCode")
- public String getVerifyCode(@RequestParam String email) throws TemplateException, IOException, MessagingException {
- String content = EmailUtils.loadEmailContent(email, getCode());
- emailUtils.sendEmail(SUBJECT,content,email);
- return "OK";
- }
-
- /**
- * 获取邮箱验证码
- * @return
- */
- public String getCode(){
- return String.valueOf((int)((Math.random() * 9 + 1) * Math.pow(10,5)));
- }
-
- }
调用接口
查看邮箱,看是否发送成功
将邮箱改为异步发送,使用Spring的线程池
定义线程池配置类LnskThreadPoolConfig.java
- package com.lnsk.common.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.scheduling.annotation.EnableAsync;
- import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
-
- import java.util.concurrent.ThreadPoolExecutor;
-
- @Configuration
- @EnableAsync
- public class LnskThreadPoolConfig {
-
- /**
- * 核心线程数
- */
- private static final int CORE_POOL_SIZE = 10;
-
- /**
- * 最大线程数
- */
- private static final int MAX_POOL_SIZE = 20;
-
- /**
- * 允许线程空闲时间 默认为秒
- */
- private static final int KEEP_ALIVE_SECONDS = 60;
-
- /**
- * 缓冲队列
- */
- private static final int QUEUE_SIZE = 40;
-
- /**
- * 线程命名
- */
- private static final String THREAD_NAME_PRE = "Verify thread-";
-
- //线程池名称verifyThreadPool
- @Bean("verifyThreadPool")
- public ThreadPoolTaskExecutor getVerifyThreadPool(){
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(CORE_POOL_SIZE);
- executor.setMaxPoolSize(MAX_POOL_SIZE);
- executor.setQueueCapacity(QUEUE_SIZE);
- executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
- executor.setThreadNamePrefix(THREAD_NAME_PRE);
-
- // 线程池对拒绝任务的处理策略(抛出异常)
- executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
- // 初始化
- executor.initialize();
- return executor;
- }
-
- }
在发送验证码的方法上加入@Async("verifyThreadPool")注解,并交给Spring容器管理
!!!该注解方法不能修饰静态方法
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。