SpringBoot学习笔记(12)----SpringBoot实现多个 账号轮询发送邮件

时间:2023-02-24 09:36:29

  首先,引入发送邮件的依赖,由于freemarker自定义模板,所以也需要把freemarker的依赖引入

  pom.xml文件

<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>
</dependency>

  配置文件需要配置的信息:

spring.mail.host:smtp.qq.com
spring.mail.username:
spring.mail.password:
spring.mail.properties.mail.smtp.auth:true
spring.mail.properties.mail.debug:true

  使用qq邮箱需要开通POP3/SMTP服务,具体方法自行百度。

  实现轮询发送的类,这里主要就是将默认只保存一个用户的配置bean注入到本实例中,读取配置文件中的username和password,分割成多个用户和密码保存到队列中。重写doSend()方法实现轮询。具体代码如下:

package com.wangx.boot.mail;

import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl; import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties; /**
* 实现多账号,轮询发送
* @EnableConfigurationProperties注解将MailProperties这个保存邮件相关信息的bean注入到本类引用中
*/
@Configuration
@EnableConfigurationProperties(MailProperties.class)
public class WangxJavaMailSenderImpl extends JavaMailSenderImpl implements JavaMailSender { //保存多个用户名和密码的队列
private ArrayList<String> usernameList;
private ArrayList<String> passwordList;
//轮询标识
private int currentMailId = 0; private final MailProperties properties; public WangxJavaMailSenderImpl(MailProperties properties) {
this.properties = properties; // 初始化账号
if (usernameList == null)
usernameList = new ArrayList<String>();
String[] userNames = this.properties.getUsername().split(",");
if (userNames != null) {
for (String user : userNames) {
usernameList.add(user);
}
} // 初始化密码
if (passwordList == null)
passwordList = new ArrayList<String>();
String[] passwords = this.properties.getPassword().split(",");
if (passwords != null) {
for (String pw : passwords) {
passwordList.add(pw);
}
}
} @Override
protected void doSend(MimeMessage[] mimeMessage, Object[] object) throws MailException { super.setUsername(usernameList.get(currentMailId));
super.setPassword(passwordList.get(currentMailId)); // 设置编码和各种参数
super.setHost(this.properties.getHost());
super.setDefaultEncoding(this.properties.getDefaultEncoding().name());
super.setJavaMailProperties(asProperties(this.properties.getProperties()));
super.doSend(mimeMessage, object); // 轮询
currentMailId = (currentMailId + 1) % usernameList.size();
} private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
} @Override
public String getUsername() {
return usernameList.get(currentMailId);
} }

  实现模板加入模板发送的方法,主要是先定义好模板,然后将模板解析成字符串,组装MimeMessage对象,调用JavaMailSenderImpl的send方法发送,具体实现代码如下

package com.wangx.boot.component;

import com.wangx.boot.mail.WangxJavaMailSenderImpl;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map; /**
*
*/
@Component
public class WangxJavaMailComponent {
private static final String template = "mail/wangx.ftl"; @Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@Autowired
private WangxJavaMailSenderImpl wangxJavaMailSender; public void sendMail(String email) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("email", email);
try {
//获取解析到的模板的字符串
String text = getTextByTemplate(template, map);
send(email, text);
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 解析模板文件,并将参数传入生成动态的字符串文返回
* @param template
* @param model
* @return
* @throws IOException
* @throws TemplateException
*/
private String getTextByTemplate(String template, Map<String, Object> model) throws IOException, TemplateException {
return FreeMarkerTemplateUtils.processTemplateIntoString(freeMarkerConfigurer.getConfiguration().getTemplate(template), model);
} /**
* 组装 MimeMessage 对象并调用wangxJavaMailSender的send方法发送,在send方法中会调用我们angxJavaMailSenderW中重写的doSend方法
* @param email
* @param text
* @return
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
private String send(String email, String text) throws MessagingException, UnsupportedEncodingException {
MimeMessage message = wangxJavaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
InternetAddress from = new InternetAddress();
from.setAddress(wangxJavaMailSender.getUsername());
from.setPersonal("Wangx", "UTF-8");
helper.setFrom(from);
helper.setTo(email);
helper.setSubject("测试邮件");
helper.setText(text, true);
wangxJavaMailSender.send(message);
return text;
} }

  测试发送的接口

package com.wangx.boot.controller;

import com.wangx.boot.component.WangxJavaMailComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/mail")
public class MailController { @Autowired
private WangxJavaMailComponent wangxJavaMailComponent;
@RequestMapping("/send")
@ResponseBody
public String send(String mail) {
wangxJavaMailComponent.sendMail(mail);
return "success";
}
}

  访问http://localhost:8080/mail/send?mail=要发送的邮箱 即可发送邮件到你制定的邮箱。

SpringBoot学习笔记(12)----SpringBoot实现多个 账号轮询发送邮件的更多相关文章

  1. SpringBoot学习笔记&lpar;6&rpar; SpringBoot数据缓存Cache &lbrack;Guava和Redis实现&rsqb;

    https://blog.csdn.net/a67474506/article/details/52608855 Spring定义了org.springframework.cache.CacheMan ...

  2. springboot学习笔记-5 springboot整合shiro

    shiro是一个权限框架,具体的使用可以查看其官网 http://shiro.apache.org/  它提供了很方便的权限认证和登录的功能. 而springboot作为一个开源框架,必然提供了和sh ...

  3. springboot学习笔记-6 springboot整合RabbitMQ

    一 RabbitMQ的介绍 RabbitMQ是消息中间件的一种,消息中间件即分布式系统中完成消息的发送和接收的基础软件.这些软件有很多,包括ActiveMQ(apache公司的),RocketMQ(阿 ...

  4. 【转】SpringBoot学习笔记&lpar;7&rpar; SpringBoot整合Dubbo&lpar;使用yml配置&rpar;

    http://blog.csdn.net/a67474506/article/details/61640548 Dubbo是什么东西我这里就不详细介绍了,自己可以去谷歌 SpringBoot整合Dub ...

  5. SpringBoot学习笔记&lpar;16&rpar;----SpringBoot整合Swagger2

    Swagger 是一个规范和完整的框架,用于生成,描述,调用和可视化RESTful风格的web服务 http://swagger.io Springfox的前身是swagger-springmvc,是 ...

  6. SpringBoot学习笔记&lpar;15&rpar;----SpringBoot使用Druid

    直接访问Druid官网wiki,有详细教程,地址如下: SpringBoot支持Druid地址:https://github.com/alibaba/druid/tree/master/druid-s ...

  7. SpringBoot学习笔记&lpar;11&rpar;-----SpringBoot中使用rabbitmq&comma;activemq消息队列和rest服务的调用

    1. activemq 首先引入依赖 pom.xml文件 <dependency> <groupId>org.springframework.boot</groupId& ...

  8. SpringBoot学习笔记&lpar;10&rpar;-----SpringBoot中使用Redis&sol;Mongodb和缓存Ehcache缓存和redis缓存

    1. 使用Redis 在使用redis之前,首先要保证安装或有redis的服务器,接下就是引入redis依赖. pom.xml文件如下 <dependency> <groupId&g ...

  9. SpringBoot学习笔记&lpar;9&rpar;----SpringBoot中使用关系型数据库以及事务处理

    在实际的运用开发中,跟数据库之间的交互是必不可少的,SpringBoot也提供了两种跟数据库交互的方式. 1. 使用JdbcTemplate 在SpringBoot中提供了JdbcTemplate模板 ...

随机推荐

  1. MSER算法介绍

    MSER代码编译: matlabroot %如果是VS2010则解压VS2010MEX支持文件到MATLAB根目录 unzip('E:\Software\develop Tools\VS2010MEX ...

  2. On Explainability of Deep Neural Networks

    On Explainability of Deep Neural Networks « Learning F# Functional Data Structures and Algorithms is ...

  3. Ajax编程相对路径与绝对路径

    http://www.worlduc.com/blog2012.aspx?bid=16946309 ajax同一域名调用采用相对路径 var url = 'QuerySingleDataByField ...

  4. android apk反编译

    ★反编译所需工具 1.AXMLPrinter.jar 2.d2j-dex2jar.bat 3.查看Jar包的GUI工具 ★功能实现 ◇解压缩 apk文件其实就是一个MIME为zip的压缩包,可以用wi ...

  5. C语言星号的秘密

    C语言星号的秘密 星号的秘密 1.乘法运算符   2.定义指针 int *p = 0; 还是 int* p = 0;? 后一种比较容易这样理解:定义了一个变量p,它是指针型的(更详细一点,是指向int ...

  6. canvas粒子时钟

    前面的话 本文将使用canvas实现粒子时钟效果 效果展示 点阵数字 digit.js是一个三维数组,包含的是0到9以及冒号(digit[10])的二维点阵.每个数字的点阵表示是7*10大小的二维数组 ...

  7. C实现 C&plus;&plus; map

    文章链接:http://blog.chinaunix.net/uid-21457204-id-3063180.html

  8. Linux下网卡绑定模式

    Linux bonding驱动一共提供了7种模式,它们分别是:balance-rr .active-backup.balance-xor.broadcast.802.3ad.balance-tlb.b ...

  9. 初识Linq to Entity

    技术介绍: LINQ(Language Integrated Query,语言集成查询)是一组用于C#和VB.NET语言的扩展,它允许编写C#或者VB.net代码,以与查询数据库相同的方式操作内存数据 ...

  10. MYC编译器源码分析之程序入口

    前文.NET框架源码解读之MYC编译器讲了MyC编译器的架构,整个编译器是用C#语言写的,上图列出了MyC编译器编译一个C源文件的过程,编译主路径如下: 首先是入口Main函数用来解析命令行参数,读取 ...