• 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实现多个 账号轮询发送邮件

  • 相关阅读:
    洛谷P2330: [SCOI2005]繁忙的都市(最小生成树)
    洛谷P1019: 单词接龙(dfs)
    洛谷P1019: 单词接龙(dfs)
    hdu1598:find the most comfortable road(并查集)
    hdu1598:find the most comfortable road(并查集)
    洛谷P1616 :疯狂的采药(完全背包)
    洛谷P1616 :疯狂的采药(完全背包)
    洛谷P1119: 灾后重建(最短路)
    洛谷P1119: 灾后重建(最短路)
    1008 N的阶乘 mod P(51NOD基础题)
  • 原文地址:https://www.cnblogs.com/xiaoshen666/p/10844051.html
Copyright © 2020-2023  润新知