无法在短时间内发送过多电子邮件

时间:2017-04-18 08:08:08

标签: java email smtp javamail exchange-server

我有一个通信应用程序,每个用户创建一个对应关系并将其发送给多个用户(平均发送我们2-30用户之间),每次发送我打开一个新线程并在以下流程中向用户组发送电子邮件(连接到邮件服务器>发送>关闭连接)如下:

public class EmailService {

    private String emailProtocol = null;
    private String emailHostSMTP = null;
    private String senderEmail = null;
    private String senderUser = null;
    private String senderPassword = null;
    private String senderDisplayName = null;
    private String emailPort = null;

    public void initConfig() {
        emailProtocol = GeneralServices.getConfig("emailProtocol");
        emailHostSMTP = GeneralServices.getConfig("emailHostSMTP");
        senderEmail = GeneralServices.getConfig("senderEmail");
        senderUser = GeneralServices.getConfig("senderUser");
        senderPassword = GeneralServices.getConfig("senderPassword");
        senderDisplayName = GeneralServices.getConfig("senderDisplayName");
        emailPort = GeneralServices.getConfig("emailPort");
        if (StringUtils.isBlank(emailPort))
            emailPort = "587";
    }

    public void setProps(Properties props) {

        props.put("mail.transport.protocol", emailProtocol);
        props.put("mail.smtp.host", emailHostSMTP);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", emailPort);
        if (ConfigurationUtils.isEnableStartTlsInEmail())
            props.put("mail.smtp.starttls.enable", "true");
        if (ConfigurationUtils.isEnableDebugInEmail())
            props.put("mail.debug", "true");

    }

    public void sendEmail(String toUser, String subject, String emailHtmlBody, String bannerPath) throws Exception {
        try {
            if (StringUtils.isBlank(toUser)) {
                return;
            }
            List<String> toUsers = new ArrayList<String>(1);
            toUsers.add(toUser);
            sendEmail(toUsers, null, null, subject, emailHtmlBody, bannerPath);
        } catch (Exception e) {
            throw e;
        }
    }

    public void sendEmail(String fromEmail, String fromDisplayName, List<String> toList, List<String> ccList,
            String subject, String emailBody, String filePhysicalPath, String fileName, String fileContentType)
            throws Exception {

        Transport transport = null;

        try {

            initConfig();
            MimeMultipart multipart = new MimeMultipart();
            Authenticator authenticator = new SMTPAuthenticator();
            MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
            MimeBodyPart bodyPart = new MimeBodyPart();

            String html = "";

            Properties props = System.getProperties();
            setProps(props);

            sslSocketFactory.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);

            Session session = Session.getInstance(props, authenticator);
            // session.setDebug(true);

            emailBody = emailBody + "<br/><br/>مرسل بواسطة : " + fromDisplayName;
            html = "<html><body style='text-align:right'> " + emailBody + " </body></html>";
            bodyPart.setContent(html, "text/html; charset=UTF-8");
            multipart.addBodyPart(bodyPart);

            MimeMessage message = new MimeMessage(session);

            message.setFrom(new InternetAddress(senderEmail, fromDisplayName));
            message.setReplyTo(new Address[] { new InternetAddress(fromEmail) });

            if (toList != null && toList.size() > 0) {
                for (String to : toList) {
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                }
            } else {
                throw new Exception("List of users to send email to is empty");
            }

            if (ccList != null && ccList.size() > 0) {
                for (String cc : ccList) {
                    message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
                }
            }

            // attach file
            BodyPart mimeBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filePhysicalPath);
            mimeBodyPart.setDataHandler(new DataHandler(source));
            mimeBodyPart.setFileName(MimeUtility.encodeText(fileName, "utf-8", "B"));

            multipart.addBodyPart(mimeBodyPart);
            // end of file attach

            message.setSubject(subject, "UTF-8");
            message.setContent(multipart);
            message.setSentDate(new Date());

            transport = session.getTransport(emailProtocol);
            transport.connect(senderEmail, senderPassword);
            transport.sendMessage(message, message.getAllRecipients());

        } catch (Exception ex) {
            throw ex;
        } finally {
            if (transport != null)
                transport.close();
        }

    }

    public void sendEmail(List<String> toList, List<String> ccList, List<String> bccList, String subject,
            String emailHtmlBody, String bannerPath) throws Exception {

        if ((toList == null || toList.size() == 0) && (ccList == null || ccList.size() == 0)
                && (bccList == null || bccList.size() == 0)) {
            return;
        }

        Transport transport = null;
        try {

            initConfig();
            MimeMultipart multipart = new MimeMultipart();
            Authenticator authenticator = new SMTPAuthenticator();
            MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
            MimeBodyPart bodyPart = new MimeBodyPart();

            String html = "";

            Properties props = System.getProperties();
            setProps(props);

            sslSocketFactory.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);

            Session session = Session.getInstance(props, authenticator);

            html = "<html><body> " + emailHtmlBody + " </body></html>";
            bodyPart.setContent(html, "text/html; charset=UTF-8");
            multipart.addBodyPart(bodyPart);

            // add banner path
            bodyPart = new MimeBodyPart();
            DataSource ds = new FileDataSource(bannerPath);
            bodyPart.setDataHandler(new DataHandler(ds));
            bodyPart.setHeader("Content-ID", "<MOAMALAT_LOGO>");
            multipart.addBodyPart(bodyPart);

            MimeMessage message = new MimeMessage(session);

            message.setFrom(new InternetAddress(senderEmail, senderDisplayName));
            message.setReplyTo(new Address[] { new InternetAddress(senderEmail) });

            if (toList != null && toList.size() > 0) {
                for (String email : toList)
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            }

            if (ccList != null && ccList.size() > 0) {
                for (String email : ccList)
                    message.addRecipient(Message.RecipientType.CC, new InternetAddress(email));
            }

            if (bccList != null && bccList.size() > 0) {
                for (String email : bccList)
                    message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email));
            }

            message.setSubject(subject, "UTF-8");
            message.setContent(multipart);
            message.setSentDate(new Date());

            transport = session.getTransport(emailProtocol);
            transport.connect(senderEmail, senderPassword);
            transport.sendMessage(message, message.getAllRecipients());

        } catch (Exception ex) {
            throw ex;
        } finally {
            if (transport != null)
                transport.close();
        }

    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = senderUser;

            String password = senderPassword;
            return new PasswordAuthentication(username, password);
        }
    }
}

有时我会收到错误:

com.sun.mail.smtp.SMTPSendFailedException: 421 4.4.2 Message submission rate for this client has exceeded the configured limit

但在与Exchange Server管理员进行审核后,他说我没有发送超出限制的电子邮件。

有时我也会收到错误:

java.net.SocketException: Connection reset

有时我也会得到:

javax.mail.MessagingException: Can't send command to SMTP host,Caused by: java.net.SocketException: Connection closed by remote host

您建议解决上述问题的解决方案是什么?

我读到有些人将传输对象设为静态并只连接到交换服务器一次,然后重复使用它,这有助于解决问题吗?连接打开多长时间?

我还想到了一个解决方案,可以将电子邮件详细信息保存在数据库表中,并让工作类定期批量发送电子邮件。

请告知如何解决此问题。

3 个答案:

答案 0 :(得分:2)

我编辑了你第二次声明的 sendEmail 方法(如下所示)。如果您喜欢它,请将相同的技术应用于其他sendEmail方法。

作为一个解决方案,我抓住了sendMessage部分进入cc列表的for循环。因此,对于每个“到”电子邮件和每个相应的“cc”电子邮件,将发送电子邮件。您也必须评估是否缺少cc列表。代码可能没有编译,但你应该看到这一点。

def __multiprocess(las_point_array, point_array, empty, tree):

    pool = Pool(os.cpu_count()) 

    args_list = [
        [j, point_array, empty, tree]
        for j in las_point_array
    ]

    results = pool.map(__pure_calc, args_list)

    #close the pool and wait for the work to finish 
    pool.close() 
    pool.join() 

    return results

答案 1 :(得分:2)

以下代码必须只运行一次,而不是每次sendEmail调用:

    initConfig()

    transport = session.getTransport(emailProtocol);
    transport.connect(senderEmail, senderPassword);

我会创建一个工厂类,它将初始化并返回一个传输实例,因此我可以使用和重用来维护与MX的多个连接,

设置会话和传输必须在进行任何sendEmail调用之前完成,因此构造函数适合您。

你可以利用会话和传输对象的小对象池,每次调用sendEmail方法都必须从池中获取一个传输实例,并在完成后将其返回池中,这样可以确保在并发请求环境中轻松加载, 进一步推断批量推动限制,首先增加推动之间的时间间隔,减少时间间隔,以便知道接近推送之间的MX准确限制,并将其与推尺寸相关联以定义最终限制。

答案 2 :(得分:1)

根据错误消息:

  

此客户端的邮件提交率已超过配置   限制

1)。 这可能是由Exchange trotting policy引起的,而here通常是Exchange管理员所不知道的(如trotting policy所述)。

因此,让您的Exchange管理员通过以下方式控制new trotting policy内的 MessageRateLimit

Get-ThrottlingPolicy | select Name,MessageRateLimit

因为Microsoft将此参数记录为:

  

MessageRateLimit参数指定每个消息的数量   可以由POP3或IMAP4客户端提交传输的分钟   使用SMTP。如果客户提交,则会收到暂时性错误   消息的速率超过此参数的值。交换   尝试在以后连接并发送消息。

低值可能会导致此问题。 Exchange管理员还可以仅为您正在使用的此任务用户创建具有更高值的here,这不会导致现有用户出现任何问题(有关示例,请参阅{{3}})。因此无需更改默认的小跑策略。

更新: 2.) 在您现在检查小跑策略时,另一种解决方案可能是控制/监视SMTP流量的SMTP解决方案。这可能与客户端相关或服务器端相关(取决于您的环境)。这里可能的选择是:防火墙&amp; AntivirusClients