How do I send mail using the non-standard sun.net.smtp.SmtpClient class?

John Zukowski

Sun's Java runtime environments (as well as the ones included with Netscape Communicator and Internet Explorer) include the SmtpClient class. As part of the sun.net package, it is not a standard Java library. However, since it is available, you may wish to use it to send mail, without going for the full fledged JavaMail installation.

The following program demonstrates how to send mail with the class:

import sun.net.smtp.SmtpClient;
import java.io.PrintStream;

public class SmtpClientExample {
  public static void main (String args[]) 
      throws Exception {
    String host = args[0];
    String from = args[1];
    String to = args[2];

    SmtpClient smtp = new SmtpClient(host);

    PrintStream msg = smtp.startMessage();
    msg.println("To: " + to);
    msg.println("Subject: Hello SmtpClient");

// blank line between headers and message
    msg.println("This is a test message.");