聯系我們 - 廣告服務 - 聯系電話:
您的當前位置: > 關注 > > 正文

環球即時看!QQ郵箱發郵件受限制怎么辦?SMTP發送郵件限制的解決方案

來源:CSDN 時間:2023-01-28 13:55:06

由于QQ郵箱對于SMTP服務發送郵件做了限制,每分鐘發送40封之后會被限制不能再發送,對于這樣的限制又需要發送大量郵件的時候的解決方案如下


(相關資料圖)

使用多個郵箱輪換使用進行發送

1、將使用的郵箱存儲在一個統一的字符串變量中,將所有可使用的郵箱存儲在一個字符串數組中(我的三個郵箱授權碼相同,如果授權碼不同,則建立一個授權碼數組,和郵箱切換的解決方案同理)

全局變量(發郵件使用的郵箱)

private static String FPAMail="freeprogramming@qq.com";

可使用的郵箱數組

private static String FPAMailArray[]={"freeprogramming@qq.com","humorchen@vip.qq.com","3301633914@qq.com"};

2、將建立連接的代碼封裝到一個函數,將連接對象變為成員變量,全局化,即每次調用同一個變量,而變量的對象可能不相同(會變化)

連接相關對象變為全局變量

private static Properties props;    private static Session mailSession;    private static MimeMessage message;    private static Transport transport;

建立連接的函數

private void init()    {        System.out.println("QQ郵件服務初始化開始:賬號"+FPAMail);        Date start=new Date();        try {            // 創建Properties 類用于記錄郵箱的一些屬性            props = new Properties();            // 表示SMTP發送郵件,必須進行身份驗證            props.put("mail.smtp.auth", "true");            //此處填寫SMTP服務器            props.put("mail.smtp.host", "smtp.qq.com");            //端口號,QQ郵箱給出了兩個端口,但是另一個我一直使用不了,所以就給出這一個587            props.put("mail.smtp.port", "587");            // 此處填寫你的賬號            props.put("mail.user",FPAMail );            // 此處的密碼就是前面說的16位STMP口令            props.put("mail.password", FPAMailPwd);            // 構建授權信息,用于進行SMTP進行身份驗證            Authenticator authenticator = new Authenticator() {                protected PasswordAuthentication getPasswordAuthentication() {                    // 用戶名、密碼                    String userName = props.getProperty("mail.user");                    String password = props.getProperty("mail.password");                    return new PasswordAuthentication(userName, password);                }            };            // 使用環境屬性和授權信息,創建郵件會話            mailSession = Session.getInstance(props, authenticator);// 創建郵件消息            message = new MimeMessage(mailSession);            // 設置發件人            InternetAddress form = new InternetAddress(                    props.getProperty("mail.user"),NickName,"utf-8");            message.setFrom(form);        }catch (Exception e)        {            e.printStackTrace();        }        Date end=new Date();        System.out.println("QQ郵件發送會話初始化成功,耗時"+((end.getTime()-start.getTime()))+"毫秒");    }

(不懂這幾個對象是干嘛的百度)

3、設置每發送20封郵件切換一次郵箱,封裝成函數

函數如下:

private void switchMail(){    int i=0;    for (;i

4、每次發送郵件的時候做判斷(i%20==0)

public void sendToAllMember(String title,String html_content)    {        System.out.println("發送郵件給所有會員");        int i=1;        for (String mail: MemberQQMailData.mails)        {            System.out.println("正在處理第"+(i++)+"個"+"剩余"+(MemberQQMailData.mails.length-i+1)+"個,正在發送給:"+mail);            sendQQMail(title,MailContentGenerator.QQMailNotice(title,html_content),mail);            if (i%20==0)                switchMail();        }    }

(MemberQQMailData.mails是一個字符串數組,存有所有會員的QQ郵箱)

效果圖:每到第20封郵件就換一個郵箱進行發送,完美解決QQ郵箱發送限制問題

新版解決方案代碼工具類

新版工具類代碼

package cn.freeprogramming.util;import cn.hutool.core.date.StopWatch;import lombok.extern.slf4j.Slf4j;import org.springframework.scheduling.annotation.Async;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import java.util.ArrayList;import java.util.List;import java.util.Objects;import java.util.Properties;import java.util.concurrent.locks.ReentrantLock;/** * QQ郵件發送工具 * * @Author:humorchen * @Date 2022/1/3 20:50 */@Slf4jpublic class QQMailUtil {    /**     * 超時時間     */    private long TIMEOUT = 5000;    /**     * 重試次數     */    private int RETRY_LIMIT = 10;    /**     * 使用第多少個賬號(QQ每個賬號限制頻率了)     */    private int accountIndex = 0;    /**     * 鎖     */    private ReentrantLock lock = new ReentrantLock(true);    /**     * 賬號列表     */    private List accountList = new ArrayList<>();    /**     * 配置列表     */    private List propertiesList = new ArrayList<>();    /**     * 授權器     */    private List authenticatorList = new ArrayList<>();    /**     * 會話列表     */    private List sessionList = new ArrayList<>();    /**     * 消息對象列表     */    private List messageList = new ArrayList<>();    /**     * 發件人地址信息列表     */    private List internetAddressArrayList = new ArrayList<>();    /**     * 發送器列表     */    private List transportList = new ArrayList<>();    /**     * 切換發件使用的郵箱下標     */    private void changeUsingAccountIndex() {        if (accountIndex == accountList.size() - 1) {            accountIndex = 0;        } else {            accountIndex++;        }    }    /**     * 與QQ郵箱服務器建立連接     *     * @throws Exception     */    private void connect() throws Exception {        QQMailAccount qqMailAccount = accountList.get(accountIndex);        Properties properties = propertiesList.get(accountIndex);        Authenticator authenticator = authenticatorList.get(accountIndex);        Session session = Session.getInstance(properties, authenticator);        MimeMessage message = new MimeMessage(session);        InternetAddress senderInternetAddress = internetAddressArrayList.get(accountIndex);        // 設置發件人        InternetAddress fromInternetAddress = new InternetAddress(                qqMailAccount.getAccount(), qqMailAccount.getNickname(), "utf-8");        message.setFrom(fromInternetAddress);        sessionList.set(accountIndex, session);        messageList.set(accountIndex, message);        Transport transport = session.getTransport(senderInternetAddress);        transport.connect();        log.info("isConnected {}", transport.isConnected());        if (accountIndex < transportList.size()) {            transportList.set(accountIndex, transport);        } else {            transportList.add(transport);        }    }    /**     * 發送郵件方法     * 由線程池處理     *     * @param title        郵件標題     * @param html_content 郵件內容(支持html,圖片等內容可能會被攔截,需要用戶點擊查看才能看到,或者讓用戶設置信任這個郵箱)     * @param receiver     收件人郵箱     */    @Async    public void sendQQMail(String title, String html_content, String receiver) {        StopWatch stopWatch = new StopWatch();        try {            lock.lock();            log.info("發送郵件給 {} ,標題:{} ,\n內容:{}", receiver, title, html_content);            stopWatch.start();            QQMailAccount qqMailAccount = accountList.get(accountIndex);            Transport transport = transportList.get(accountIndex);            MimeMessage message = messageList.get(accountIndex);            if (transport == null || !transport.isConnected()) {                connect();            }            stopWatch.stop();            log.info("連接花費 {}ms", stopWatch.getTotalTimeMillis());            stopWatch.start();            // 設置收件人的郵箱            message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver));            // 設置郵件標題            message.setSubject(title, "utf-8");            // 設置郵件的內容體            message.setContent(html_content, "text/html;charset=UTF-8");            try {                //保存修改                message.saveChanges();                //發送郵件                transport.sendMessage(message, new InternetAddress[]{new InternetAddress(receiver)});                stopWatch.stop();                log.info("使用郵箱:{} 發送成功,花費時間:{}ms", qqMailAccount.getAccount(), stopWatch.getTotalTimeMillis());            } catch (Exception e) {                //由于被騰訊方面因超時被關閉連接屬于正常情況                log.info("郵件發送失敗,正在嘗試和QQ郵件服務器重新建立鏈接");                stopWatch.stop();                stopWatch.start();                boolean success = false;                for (int i = 1; i <= RETRY_LIMIT; i++) {                    try {                        connect();                        log.info("使用郵箱:{} 成功建立鏈接", qqMailAccount.getAccount());                        transport = transportList.get(accountIndex);                        message = messageList.get(accountIndex);                        success = true;                        break;                    } catch (Exception ee) {                        changeUsingAccountIndex();                        qqMailAccount = accountList.get(accountIndex);                        log.info("鏈接建立失敗,切換到郵箱:{} ,進行第 {} 次重試..." + qqMailAccount.getAccount(), i);                    }                }                if (success) {                    // 設置收件人的郵箱                    message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver));                    // 設置郵件標題                    message.setSubject(title, "utf-8");                    // 設置郵件的內容體                    message.setContent(html_content, "text/html;charset=UTF-8");                    message.saveChanges();                    transport.sendMessage(message, new InternetAddress[]{new InternetAddress(receiver)});                    stopWatch.stop();                    log.info("重建連接后使用郵箱:{} 發送成功,耗費時間:{}ms", qqMailAccount.getAccount(), stopWatch.getTotalTimeMillis());                } else {                    log.error("鏈接多次嘗試后無法建立,郵件發送失??!");                    return;                }            }        } catch (Exception e) {            log.error("sendQQMail", e);        } finally {            lock.unlock();            if (stopWatch.isRunning()) {                stopWatch.stop();            }        }    }    /**     * 添加賬號     */    public void addAccount(String account, String authorizationCode, String nickname) {        int oldAccountIndex = accountIndex;        boolean addFinished = false;        try {            lock.lock();            oldAccountIndex = accountIndex;            accountIndex = accountList.size();            QQMailAccount qqMailAccount = new QQMailAccount(account, authorizationCode, nickname);            Properties properties = createProperties(qqMailAccount);            Authenticator authenticator = createAuthenticator(qqMailAccount);            // 使用環境屬性和授權信息,創建郵件會話            Session session = Session.getInstance(properties, authenticator);            MimeMessage message = new MimeMessage(session);            // 設置發件人            InternetAddress internetAddress = new InternetAddress(                    account, nickname, "utf-8");            message.setFrom(internetAddress);            Transport transport = session.getTransport(new InternetAddress(qqMailAccount.getAccount()));            transport.connect();            accountList.add(qqMailAccount);            propertiesList.add(properties);            authenticatorList.add(authenticator);            sessionList.add(session);            transportList.add(transport);            messageList.add(message);            internetAddressArrayList.add(internetAddress);            addFinished = true;        } catch (Exception e) {            //移除已經加入的            if (addFinished) {                accountList.remove(accountIndex);                propertiesList.remove(accountIndex);                authenticatorList.remove(accountIndex);                sessionList.remove(accountIndex);                transportList.remove(accountIndex);                messageList.remove(accountIndex);                internetAddressArrayList.remove(accountIndex);            }            log.error("addAccount", e);        } finally {            accountIndex = oldAccountIndex;            lock.unlock();        }    }    /**     * 創建配置文件     *     * @param qqMailAccount     * @return     */    private Properties createProperties(QQMailAccount qqMailAccount) {        // 創建Properties 類用于記錄郵箱的一些屬性        Properties properties = new Properties();        // 表示SMTP發送郵件,必須進行身份驗證        properties.put("mail.smtp.auth", "true");        //此處填寫SMTP服務器        properties.put("mail.smtp.host", "smtp.qq.com");        //端口號,QQ郵箱給出了兩個端口,但是另一個我一直使用不了,所以就給出這一個587        properties.put("mail.smtp.port", "587");        // 此處填寫你的賬號        properties.put("mail.user", qqMailAccount.getAccount());        // 此處的密碼就是前面說的16位STMP口令        properties.put("mail.password", qqMailAccount.getAuthorizationCode());        //設置超時時間        properties.put("mail.smtp.timeout", "" + TIMEOUT);        return properties;    }    /**     * 創建授權信息對象     *     * @param qqMailAccount     * @return     */    private Authenticator createAuthenticator(QQMailAccount qqMailAccount) {        // 構建授權信息,用于進行SMTP進行身份驗證        Authenticator authenticator = new Authenticator() {            @Override            protected PasswordAuthentication getPasswordAuthentication() {                // 用戶名、密碼                String userName = qqMailAccount.getAccount();                String password = qqMailAccount.getAuthorizationCode();                return new PasswordAuthentication(userName, password);            }        };        return authenticator;    }    private static class QQMailAccount {        /**         * 賬號         */        private String account;        /**         * 授權碼         */        private String authorizationCode;        /**         * 發送者昵稱         */        private String nickname;        public QQMailAccount(String account, String authorizationCode, String nickname) {            this.account = account;            this.authorizationCode = authorizationCode;            this.nickname = nickname;        }        public String getAccount() {            return account;        }        public void setAccount(String account) {            this.account = account;        }        public String getAuthorizationCode() {            return authorizationCode;        }        public void setAuthorizationCode(String authorizationCode) {            this.authorizationCode = authorizationCode;        }        public String getNickname() {            return nickname;        }        public void setNickname(String nickname) {            this.nickname = nickname;        }        @Override        public boolean equals(Object o) {            if (this == o) return true;            if (o == null || getClass() != o.getClass()) return false;            QQMailAccount that = (QQMailAccount) o;            return Objects.equals(account, that.account) && Objects.equals(authorizationCode, that.authorizationCode) && Objects.equals(nickname, that.nickname);        }        @Override        public int hashCode() {            return Objects.hash(account, authorizationCode, nickname);        }    }}

配置工具類對象到容器

package cn.freeprogramming.config;import cn.freeprogramming.util.QQMailUtil;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * QQ郵件配置 * * @Author:humorchen * @Date 2022/1/3 21:54 */@Configurationpublic class QQMailConfig {    //授權碼,在QQ郵箱里設置    private String authorizationCode = "hkkm123kasbjbf";    private String nickname = "自由編程協會";    @Bean    public QQMailUtil qqMailUtil() {        QQMailUtil qqMailUtil = new QQMailUtil();        qqMailUtil.addAccount("freeprogramming@qq.com", authorizationCode, nickname);        qqMailUtil.addAccount("freeprogramming@foxmail.com", authorizationCode, nickname);        qqMailUtil.addAccount("357341307@qq.com", authorizationCode, nickname);        return qqMailUtil;    }}
責任編輯:

標簽: 發送郵件

相關推薦:

精彩放送:

新聞聚焦
Top 岛国精品在线