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=要發送的郵箱 即可發送郵件到你制定的郵箱。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM