How to send several letters in one session?

I want to send thousands of different emails to different recipients and would like to open a connection to my SMTP and keep it on. Hope this is faster than reconnecting for ervy mail. I would like to use Apache Commons Email for this, but may return to the Java Mail API if necessary.

Now I am doing this, which opens closing 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("test@example.com"); email.addTo(to); email.setSubject(subject); email.setHtmlMsg(htmlMsg); email.send(); 
+7
java email apache-commons-email
source share
3 answers

Here is my performance testing class. Sending mail using one connection is 4 times faster, and then re-opening the connection each time (what happens when you use regular mail). Performance can be increased 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(); 
+18
source share

You can use your previous code, but add the following to get the basic session

 email.getMailSession(); 

You can add additional properties to java mail with

 email.getMailSession().getProperties().put(<key>, <value>); 
+3
source share

Take 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 messages before calling the close () function on the transport.

+1
source share

All Articles