与 smtp 服务器的连接池

connection pooling with smtp servers

比如我有 5 台 smtp 服务器,我想批量发送邮件并希望在每台服务器上 post 那么我该如何实现呢? 我现在是这样使用的:

String smtpHost=”smtp.gmail.com”;
javaMailSender.setHost(smtpHost);
Properties mailProps = new Properties();
mailProps.put(“mail.smtp.connectiontimeout”, “2000”);
mailProps.put(“mail.smtp.timeout”, “2000”);
mailProps.put(“mail.debug”, “false”);
javaMailSender.setJavaMailProperties(mailProps);

现在我想post多个VIP点赞

String smtpHost=”192.168.xx.xx,192.168.xx.xx,192.168.xx.xx”;

你能建议我如何实现吗?

您可以使用 SmtpConnectionPool

使用不同服务器的属性创建会话,例如

Properties mailServerProperties = new Properties();
mailServerProperties.put("mail.smtp.port",String.valueOf(port));
Session session = Session.getDefaultInstance(mailServerProperties);

在应用程序开始时为每个 IP 创建 SmtpConnectionPool

GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(5);

SmtpConnectionFactory smtpConnectionFactory = SmtpConnectionFactoryBuilder.newSmtpBuilder()
                                             .session(session).port(port).protocol("smtp")
                                                .build();
SmtpConnectionPool smtpConnectionPool = new SmtpConnectionPool(smtpConnectionFactory, config);

然后您可以在映射中查看每个 IP 的池

pools.put(ip, smtpConnectionPool);

在发送邮件时,您可以从 Map 中获取一个池,然后从池中借用一个连接并发送您的邮件。

SmtpConnectionPool smtpConnectionPool = pools.get(ip);
try (ClosableSmtpConnection transport = smtpConnectionPool.borrowObject()) {

    MimeMessage mimeMessage = new MimeMessage(transport.getSession());
    mimeMessage.setFrom(new InternetAddress(email.getFrom()));
    mimeMessage.addRecipients(MimeMessage.RecipientType.TO, Util.getAddresses(email.getTo()));
    mimeMessage.setSubject(email.getSubject());
    mimeMessage.setContent(email.getBody(), "text/html");
    transport.sendMessage(mimeMessage);
} catch (Exception e) {
    e.printStackTrace();
}

您还应该考虑采用某种队列排序机制,因为发送群发电子邮件应该是一项后台工作。