java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot发送异步邮件

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

作者:Splaying

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

1、基本简介

<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、编写邮件工具类

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发送异步邮件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文