Javamail, Transport.send() very slow

mitch picture mitch · Sep 20, 2012 · Viewed 11.6k times · Source

I have written a method for sending emails in bulk but it is very very slow (around 3 mails every 10 seconds). I want to send thousands of mails. Is there any way to do this much more faster?

I am using gmail now but only for test, finally I want to send using my own SMTP server.

Here is the code:

public boolean sendMessages()
{
    try 
    {
        Session session = Session.getInstance(this._properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                 return new PasswordAuthentication("user", "password");
            }
        });
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(this.getFrom()));


        message.setSubject(this.getSubject());
        message.setText(this.getBody());                
        for (int i = 0, c = this._addresses.size(); i < c; i++)
        {
            message.setRecipient(Message.RecipientType.TO,  new InternetAddress(this._addresses.get(i)));                    
            Transport.send(message);
        }
        return true;
     } 
     catch(AuthenticationFailedException e) {
         e.printStackTrace();
           return false;
     }
     catch(MessagingException e) {
         e.printStackTrace();
           return false;
     }
}

Answer

mitch picture mitch · Sep 24, 2012

Ok, thank you for your suggestions.

My solution is:

Transport transport = session.getTransport("smtp");
transport.connect(this._properties.getProperty("mail.smtp.host"), 
Integer.parseInt(this._properties.getProperty("mail.smtp.port")),
    this._properties.getProperty("mail.smtp.user"),
    this._properties.getProperty("mail.smtp.password"));

Address[] addr = new Address[this._addresses.size()];
for (int i = 0, c = this._addresses.size(); i < c; i++)
{
    addr[i] = new InternetAddress(this._addresses.get(i));
}

transport.sendMessage(message, addr);