6

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;
     }
}
Asciiom
  • 9,867
  • 7
  • 38
  • 57
mitch
  • 2,235
  • 3
  • 27
  • 46
  • I would expect the limitation is how fast the server will accept emails. You should expect your own mail server handle well over 10 per second. – Peter Lawrey Sep 20 '12 at 15:23
  • 2
    You can measure how fast JavaMail can create messages by replacing the Transport.send call with: message.saveChanges(); message.writeTo(new BufferedOutputStream(new FileOutputStream("msg.txt"))); If sending to your server is slower than that, it's most likely due to network performance, protocol overhead, or the speed of your server. – Bill Shannon Sep 20 '12 at 17:31
  • 1
    [`MimeMessage.saveChanges` can trigger a DNS lookup](https://stackoverflow.com/questions/44435457/mimemessage-savechanges-is-really-slow) which will throw off your benchmark. – jmehrens Jun 08 '17 at 15:38

1 Answers1

7

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);
Elon Than
  • 9,603
  • 4
  • 27
  • 37
mitch
  • 2,235
  • 3
  • 27
  • 46