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);
现在我想在多个VIP上张贴
String smtpHost=”192.168.xx.xx,192.168.xx.xx,192.168.xx.xx”;
你能建议我如何实现这个目标吗?
答案 0 :(得分:1)
您可以使用SmtpConnectionPool。
使用不同服务器的属性创建会话,例如
Properties mailServerProperties = new Properties();
mailServerProperties.put("mail.smtp.port",String.valueOf(port));
Session session = Session.getDefaultInstance(mailServerProperties);
创建SmtpConnectionPool说每个IP,在应用程序开始时
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);
发送邮件时,您可以从地图中获取一个池,然后从池中借用一个连接并发送邮件。
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();
}
您还应该考虑使用一些队列排序机制,因为发送批量电子邮件应该是后台工作。