Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javamail, Transport.send() very slow

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;
     }
}
like image 861
mitch Avatar asked Sep 20 '12 15:09

mitch


Video Answer


1 Answers

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);
like image 141
mitch Avatar answered Sep 17 '22 09:09

mitch