Skip to content
Advertisement

connection pooling with smtp servers

like i have 5 smtp server’s and i want to do bulk mailing and want to post on each server then how i can achieve it ? I am using like this now :

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);

Now i want to post on multiple VIP’s like

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

Can you suggest how i can achieve this ?

Advertisement

Answer

You can use SmtpConnectionPool.

Create session with properties for different servers e.g.

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

Create SmtpConnectionPool say per IP, at the start of application

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

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

You can then perisit the pools per IP in a Map

pools.put(ip, smtpConnectionPool);

While sending the mail you can grab a pool from Map and then borrow a connection from the pool and send your mail.

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();
}

You should also consider to have some queue sort mechanism in place as sending bulk email should be a background job.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement