SpringBoot学习笔记(12)----SpringBoot实现多个 账号轮询发送邮件
首先,引入发送邮件的依赖,由于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实现多个 账号轮询发送邮件的更多相关文章
- SpringBoot学习笔记(6) SpringBoot数据缓存Cache [Guava和Redis实现]
https://blog.csdn.net/a67474506/article/details/52608855 Spring定义了org.springframework.cache.CacheMan ...
- springboot学习笔记-5 springboot整合shiro
shiro是一个权限框架,具体的使用可以查看其官网 http://shiro.apache.org/ 它提供了很方便的权限认证和登录的功能. 而springboot作为一个开源框架,必然提供了和sh ...
- springboot学习笔记-6 springboot整合RabbitMQ
一 RabbitMQ的介绍 RabbitMQ是消息中间件的一种,消息中间件即分布式系统中完成消息的发送和接收的基础软件.这些软件有很多,包括ActiveMQ(apache公司的),RocketMQ(阿 ...
- 【转】SpringBoot学习笔记(7) SpringBoot整合Dubbo(使用yml配置)
http://blog.csdn.net/a67474506/article/details/61640548 Dubbo是什么东西我这里就不详细介绍了,自己可以去谷歌 SpringBoot整合Dub ...
- SpringBoot学习笔记(16)----SpringBoot整合Swagger2
Swagger 是一个规范和完整的框架,用于生成,描述,调用和可视化RESTful风格的web服务 http://swagger.io Springfox的前身是swagger-springmvc,是 ...
- SpringBoot学习笔记(15)----SpringBoot使用Druid
直接访问Druid官网wiki,有详细教程,地址如下: SpringBoot支持Druid地址:https://github.com/alibaba/druid/tree/master/druid-s ...
- SpringBoot学习笔记(11)-----SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用
1. activemq 首先引入依赖 pom.xml文件 <dependency> <groupId>org.springframework.boot</groupId& ...
- SpringBoot学习笔记(10)-----SpringBoot中使用Redis/Mongodb和缓存Ehcache缓存和redis缓存
1. 使用Redis 在使用redis之前,首先要保证安装或有redis的服务器,接下就是引入redis依赖. pom.xml文件如下 <dependency> <groupId&g ...
- SpringBoot学习笔记(9)----SpringBoot中使用关系型数据库以及事务处理
在实际的运用开发中,跟数据库之间的交互是必不可少的,SpringBoot也提供了两种跟数据库交互的方式. 1. 使用JdbcTemplate 在SpringBoot中提供了JdbcTemplate模板 ...
随机推荐
- CSS3中的2D和3D转换知识介绍
一 2D转换 转换是CSS3中具有颠覆性的特征之一,可以实现元素的位移.旋转.变形.缩放,甚至支持矩阵方式,配合即将学习的过渡和动画知识,可以取代大量之前只能靠Flash才可以实现的效果. 1.移动 ...
- WCF(二)配置文件
上篇文章中对WCF的配置放到App.config中,这样可以使程序更灵活.更具有扩展性. 下面说下配置文件中各个节点的含义. 服务端: WCF配置文件节点放在<system.serviceMod ...
- 什么是2.5D与3D编辑模式
ZBrush®其实就是一个带有三维特性的二维软件,它不仅具有绘制二维图像的功能,而且也具有对三维物体进行编辑的功能,就是所谓的2.5D(Pixol技术). 学习ZBrush之前有必要了解一下2.5D的 ...
- 转:用java调用oracle存储过程总结(比较好理解)
这段时间开始学习写存储过程,主要原因还是因为工作需要吧,本来以为很简单的,但几经挫折,豪气消磨殆尽,但总算搞通了,为了避免后来者少走弯路,特记述与此,同时亦对自己进行鼓励. 一:无返回值的存储过程 存 ...
- 让前端攻城师独立于后端进行开发: Mock.js
一.Mock.js是什么? 目前的大部分公司的项目都是采用的前后端分离, 后端接口的开发和前端人员是同时进行的. 那么这个时候就会存在一个问题, 在页面需要使用大量数据进行渲染生成前, 后端开发人员的 ...
- [LeetCode] 242. 有效的字母异位词 valid-anagram(排序)
注意这里字母异位词的定义是:字母类别及个数都要一样,只是排列顺序不同. class Solution(object): def isAnagram(self, s, t): ""& ...
- 小学生都能学会的python(深浅拷贝)
小学生都能学会的python(深浅拷贝) join() 把列表中的每一项用字符串拼接起来 # lst = ["汪峰", "吴君如", "李嘉欣&quo ...
- 紫书 例题8-3 UVa 1152(中途相遇法)
这道题要逆向思维, 就是求出答案的一部分, 然后反过去去寻找答案存不存在. 其实很多其他题都用了这道题目的方法, 自己以前都没有发现, 这道题专门考这个方法.这个方法可以没有一直往下求, 可以省去很多 ...
- COGS——T 438. 烦人的幻灯片
http://www.cogs.pro/cogs/problem/problem.php?pid=438 ★☆ 输入文件:slides.in 输出文件:slides.out 简单对比时间限 ...
- apache rewrite 正則表達式基础
用了好几次rewrite,用的次数不是非常多,每次都忘,都得又一次上网上找一堆现看,总结一下,以免以后忘了 =====================分隔符===================== ...