None

Sending Email from Java

January 28, 2010

Here's an example of code to send email from Java.

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
/**
  * A simple email sender class.
  */
public class Test
{
  /**
    * Main method to send a message given on the command line.
    */
  public static void main(String args[])
  {
    try
    {
      String smtpServer=args[0];
      String to=args[1];
      String from=args[2];
      String subject=args[3];
      String body=args[4];
      send(smtpServer, to, from, subject, body);
    }
    catch (Exception ex)
    {
       throw new RuntimeException(ex.getMessage(), ex);
    }
  }

  /**
    * "send" method to send the message.
    */
  public static void send(String smtpServer, String to, String from, String subject, String body)
  {
    try
    {
      Properties props = System.getProperties();
      // -- Attaching to default Session, or we could start a new one --
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.host", smtpServer);
      Session session = Session.getDefaultInstance(props, null);
      // -- Create a new message --
      Message msg = new MimeMessage(session);
      // -- Set the FROM and TO fields --
      msg.setFrom(new InternetAddress(from));
      msg.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse(to, false));
      // -- Set the subject and body text --
      msg.setSubject(subject);
      msg.setText(body);
      // -- Send the message --
      Transport lTransport = session .getTransport();
      lTransport.connect();
      lTransport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
      lTransport.close();
      System.out.println("Message sent OK.");
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
  }
}

SMTP Server Caching

Using the code as above, the program will use the SMTP server address once, and then always get the same address. This is because we get the default session:

Session lMailSession = Session.getDefaultInstance(lProperties, null);

This code only uses the properties the first time it is called. If you want to use the properties each time, for example if your SMTP server comes from a database and you want to be able to change it without bouncing the app, then use this instead:

Session lMailSession = Session.getInstance(lProperties, null);

Tags: java email smtp javamail