How to send multiple emails in one session?
Asked Answered
A

3

9

I want to send thousands of different emails to different recipients and would like to open the connection to my SMTP and hold it. I hope this is faster then reopen the connection for ervy mail. I would like to use Apache Commons Email for that, but could fall back to the Java Mail API if necessary.

Right now I'am doing this, what opens a closes the connection every time:

HtmlEmail email = new HtmlEmail();
email.setHostName(server.getHostName());
email.setSmtpPort(server.getPort());
email.setAuthenticator(new DefaultAuthenticator(server.getUsername(), server.getPassword()));
email.setTLS(true);
email.setFrom("[email protected]");
email.addTo(to);
email.setSubject(subject);
email.setHtmlMsg(htmlMsg);
email.send();
Artificer answered 2/12, 2010 at 12:2 Comment(3)
Keep the session open and send 1000 emails and finally close the session.Nicolettenicoli
Do you know if this is possible with commons email?Collin
it doesn't seem like it...I use JavaMail full-out.Nicolettenicoli
A
20

Here is my performance test class. Sending the mails using one connection is 4 times faster then reopen the connection every time (what happens when you use commons mail). The performance can be pushed further by using multiple threads.

    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", server);
    properties.put("mail.smtp.port", "" + port);

    Session session = Session.getInstance(properties);
    Transport transport = session.getTransport("smtp");

    transport.connect(server, username, password);

    for (int i = 0; i < count; i++) {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = {new InternetAddress(to)};
        message.setRecipients(Message.RecipientType.TO, address);

        message.setSubject(subject + "JavaMail API");
        message.setSentDate(new Date());

        setHTMLContent(message);
        message.saveChanges();
        transport.sendMessage(message, address);

    }

    transport.close();
Artificer answered 4/12, 2010 at 17:39 Comment(0)
S
3

You can use your earlier code but add the following to get the underlying Session

email.getMailSession();

You can add extra java mail properties by

email.getMailSession().getProperties().put(<key>, <value>);
Singer answered 15/10, 2012 at 16:27 Comment(0)
L
1

Have a look at http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html. There is an example showing how to send an email. You should be able to send more before calling close() on the Transport.

Levigate answered 2/12, 2010 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.