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

Mah*_*leh 9 java email exchange-server smtp jakarta-mail

我有一个通信应用程序,每个用户创建一个通信并将其发送给多个用户(平均发送我们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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有时我得到错误:

com.sun.mail.smtp.SMTPSendFailedException: 421 4.4.2 Message submission rate for this client has exceeded the configured limit
Run Code Online (Sandbox Code Playgroud)

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

有时我也得到错误:

java.net.SocketException: Connection reset
Run Code Online (Sandbox Code Playgroud)

有时我也得到:

javax.mail.MessagingException: Can't send command to SMTP host,Caused by: java.net.SocketException: Connection closed by remote host
Run Code Online (Sandbox Code Playgroud)

您提出什么解决方案来解决上述问题?

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

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

请告知如何解决此问题.

Bas*_*anW 1

根据错误信息:

\n\n
\n

该客户端的消息提交率已超过配置的\n限制

\n
\n\n

1.)\n这可能是由 Exchange 管理员通常不知道的Exchange trotting 策略引起的(如此处所述)。

\n\n

因此,让您的 Exchange 管理员通过以下方式控制trotting 策略中的MessageRateLimit

\n\n
Get-ThrottlingPolicy | select Name,MessageRateLimit\n
Run Code Online (Sandbox Code Playgroud)\n\n

因为微软将此参数记录为:

\n\n
\n

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

\n
\n\n

值太低可能会导致此问题。Exchange 管理员还可以仅针对您正在使用的此任务用户创建一个具有更高值的新小跑策略,该策略不是\xc2\xb4t,然后会导致现有用户出现任何问题(请参阅此处的示例)。所以不需要改变默认的小跑策略。

\n\n

更新:\n2.)\n当您现在检查小跑策略时,另一个解决方案可能是控制/监视 SMTP 流量的 SMTP 解决方案。这可能与客户端相关或服务器端相关(取决于您的环境)。这里可能的选项有: 防火墙和防病毒客户端

\n