SpringBoot发送异步邮件流程与实现详解

 更新时间:2024年01月04日 09:10:10   作者:Splaying  
这篇文章主要介绍了SpringBoot发送异步邮件流程与实现详解,Servlet阶段邮件发送非常的复杂,如果现代化的Java开发是那个样子该有多糟糕,现在SpringBoot中集成好了邮件发送的东西,而且操作十分简单容易上手,需要的朋友可以参考下

1、基本简介

  • Servlet阶段邮件发送非常的复杂,如果现代化的Java开发是那个样子该有多糟糕;现在SpringBoot中集成好了邮件发送的东西,而且操作十分简单容易上手。
  • 发送邮件最主要的一步是需要去对应的邮箱开启POP3/SMTP 或者 IMAP/SMTP,并且拿到授权码!
  • 导入依赖包spring-boot-starter-mail。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、邮件发送流程

首先导入mail的依赖包之后,根据SpringBoot的自动装配原理。几乎所有的Bean对象都给装配好了,直接拿来可以使用。

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ MimeMessage.class, MimeType.class, MailSender.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)	
@EnableConfigurationProperties(MailProperties.class)			//配置文件绑定
@Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class })
public class MailSenderAutoConfiguration {

	static class MailSenderCondition extends AnyNestedCondition {

		MailSenderCondition() {
			super(ConfigurationPhase.PARSE_CONFIGURATION);
		}
		// 配置文件前缀名称
		@ConditionalOnProperty(prefix = "spring.mail", name = "host")
		static class HostProperty {

		}

		@ConditionalOnProperty(prefix = "spring.mail", name = "jndi-name")
		static class JndiNameProperty {

		}
	}
}

简单分析一手可以看到只需要配置一下application文件即可,前缀以spring.mail开头;

spring:
  mail:
    username: xxxx@163.com
    password: 授权码
    host: smtp.163.com				# 不同邮箱对应的服务器不一样
    default-encoding: UTF-8
    
#    username: xxxx@qq.com
#    password: 授权码
#    host: smtp.qq.com

3、配置线程池

这个步骤不是必须的,但是使用异步的邮件建议还是配置一下。

@Configuration
@EnableAsync//开启异步
public class ThreadPoolConfig {

    @Bean("threadPool")
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量
        executor.setQueueCapacity(100);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("Thread-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

4、编写邮件工具类

  • 邮件在SpringBoot中被封装成简单纯文本邮件、多媒体邮件两种形式。
  • 针对上述两种形式的邮件可以进行编写一个工具类便于操作使用。
public class EmailUtil {

    private static final String content = "这是邮件的主内容";
	
	// 纯文本邮件
    public static SimpleMailMessage simple(String from, String to){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject("欢迎xxx");
        message.setText(content);
        return message;
    }

	// 多媒体邮件
    public static MimeMessage mimeMessage(MimeMessage message,String from, String to) throws MessagingException {
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject("复杂邮件主题");
        helper.setText("<p style='color: deepskyblue'>这是浅蓝色的文字</p>", true);
        helper.addAttachment("1.docx", new File("C:\\Users\\Splay\\Desktop\\说明书.docx"));
        helper.addAttachment("1.pdf", new File("C:\\Users\\Splay\\Desktop\\参考.pdf"));
        return message;
    }
}

5、邮件发送

邮件发送是需要时间的,因此为了不让用户等待的时间过长建议这里使用异步的形式发送。避免阻塞

@Service
public class SendEmailService {

	// SpringBoot自动装配的邮件发送实现类
    @Autowired
    JavaMailSenderImpl mailSender;

    @Async("threadPool")
    public void sendSimpleMail(String from, String to) {
        SimpleMailMessage message = EmailUtil.simple(from, to);
        mailSender.send(message);                   //简单纯文本邮件发送
    }

    @Async("threadPool")
    public void sendMultiPartMail(String from, String to) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessage mimeMessage = EmailUtil.mimeMessage(message,from, to);
        mailSender.send(mimeMessage);               //复杂邮件发送
    }

}

6、编写controller

编写几个controller进行测试

@Controller
public class RouterController {

    @Value("${spring.mail.username}")
    private String from;


    @Autowired
    SendEmailService mail;

    @RequestMapping("/simple")
    @ResponseBody
    public String simpleMail(@RequestParam(required = true,name = "mail",defaultValue = "xxx@qq.com") String to) {
        mail.sendSimpleMail(from, to);
        return "Send SimpleEmail Successful!";
    }

    @RequestMapping("/complex")
    @ResponseBody
    public String complexMail(@RequestParam(required = true,name = "mail",defaultValue = "xxx@qq.com") String to) throws MessagingException {
        mail.sendMultiPartMail(from, to);
        return "Send SimpleEmail Successful!";
    }
}

到此这篇关于SpringBoot发送异步邮件流程与实现详解的文章就介绍到这了,更多相关SpringBoot发送异步邮件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 深入解析java中的静态代理与动态代理

    深入解析java中的静态代理与动态代理

    本篇文章是对java中的静态代理与动态代理进行了详细的分析介绍,需要的朋友可以过来参考下,希望对大家有所帮助
    2013-10-10
  • 浅析java中常用的定时任务框架-单体

    浅析java中常用的定时任务框架-单体

    这篇文章主要带大家了解常用的单体应用定时任务框架以及掌握定时任务在单体中如何使用,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2021-12-12
  • 纯Java代码实现流星划过天空

    纯Java代码实现流星划过天空

    本文给大家介绍纯java代码实现流星划过天空,包括流星个数,流星飞行的速度,色阶,流星大小相关变量设置。对java流星划过天空特效代码感兴趣的朋友可以参考下本文
    2015-10-10
  • Java如何高效实现Word文档对比

    Java如何高效实现Word文档对比

    在项目协作、文档审核或版本迭代的快节奏工作中,你是否曾为Word文档的细微修改而抓狂,下面我们就来一起探讨如何利用Java进行Word文档的自动化比较吧
    2025-11-11
  • Spring Boot集成Redis Stream消息队列从入门到实战指南

    Spring Boot集成Redis Stream消息队列从入门到实战指南

    Redis Stream作为Redis 5.0引入的新数据类型,提供了完整的消息队列功能,成为轻量级消息中间件的优秀选择,本文给大家介绍Spring Boot集成Redis Stream消息队列从入门到实战指南,感兴趣的朋友跟随小编一起看看吧
    2026-03-03
  • Spring自定义注解实现数据脱敏

    Spring自定义注解实现数据脱敏

    在当今数据安全越来越受到重视的背景下,许多企业都对敏感数据的保护有着严格的要求,本文就来深入探讨一下如何自定义注解来实现对敏感数据的脱敏处理吧
    2024-11-11
  • SpringCloud Gateway使用详解

    SpringCloud Gateway使用详解

    Spring Cloud Gateway是一个基于Spring Boot 2.x和Spring WebFlux的API网关,可以帮助我们构建微服务架构中的统一入口。感兴趣的同学可以参考一下
    2023-04-04
  • java同步与异步的学习笔记整理

    java同步与异步的学习笔记整理

    在本篇文章里小编给大家整理了关于java同步与异步的学习笔记整理内容,需要的朋友们参考下。
    2020-02-02
  • java使用多线程找出最大随机数

    java使用多线程找出最大随机数

    这篇文章主要为大家详细介绍了java使用多线程找出最大随机数,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-07-07
  • Spring Boot使用和配置Druid

    Spring Boot使用和配置Druid

    本篇文章主要介绍了Spring Boot使用和配置Druid,Druid号称是Java语言中最好的数据库连接池,并且能够提供强大的监控和扩展功能
    2017-04-04

最新评论