Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www2.austin.cc.tx.us/baldwin/

Servlets, Originating Email in Servlets

Java Programming, Lecture Notes # 690, Revised 3/15/99.

Preface

Introduction

Sample Program

Interesting Code Fragments

Program Listing


Preface

Students in Prof. Baldwin's Advanced Java Programming classes at ACC will be responsible for knowing and understanding all of the material in this lesson beginning with the spring semester of 1999.

This lesson was originally written on March 15, 1999.

The sample servlet in this lesson was tested using Win95, the JDK 1.2 download package from JavaSoft, the JSDK 2.0 download package from JavaSoft, and the servletrunner program that is included in the JSDK.

Introduction

A common requirement for servlets in an HTTP environment is the ability to send email messages. There are several ways that you can accomplish this.

You can do your own socket programming in the servlet and implement a mail transfer protocol as described in a separate lesson on network programming.

You can download the JavaMail API. As of 3/15/99 the API is available at http://java.sun.com/products/javamail. This is a large API that provides far more capability that you will probably need to construct and send simple email messages from within a servlet.

You can use the unsupported class from Sun named sun.net.smtp.SmtpClient. This class is included in the JDK 1.2 download and is very easy to use. The sample program in this lesson uses this class to construct and send an email message from within a servlet.

Sample Program

Servlet06.java illustrates the ability to construct and send email messages from within a servlet. The servlet constructs and sends an email message containing some text along with the current date and time.

The email message produced by one run of the servlet was as shown below:

Subject: Test Msg from Servlet
   Date: Mon, 15 Mar 1999 14:21:21 -0500 (EST)
   From: baldwin.richard@iname.com
     To: baldwin@austin.cc.tx.us

This is a test message.
Mon Mar 15 13:20:05 CST 1999

After sending the message, the servlet reports back to the HTML client that activated the servlet that the email message has been sent.

You must be online and have access to a cooperating SMTP server to successfully execute this servlet.

The next section discusses some of the interesting code fragments that make up this servlet.

Interesting Code Fragments

The first fragment shows the import directives with particular emphasis on the last directive that imports the class used to construct and send the email message.

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import sun.net.smtp.SmtpClient;

Next we see the beginning of the doGet() method and its parameters. You have seen this in many previous lessons, so there is nothing new here.

public class Servlet06 extends HttpServlet{
  public void doGet(HttpServletRequest req, 
                    HttpServletResponse res)
                      throws ServletException, IOException{

The next several fragments show how to use the constructor and methods of the SmtpClient class to construct and send an email message. The names of the methods are generally indicative of the purpose of each method.

The next fragment instantiates an object of the SmtpClient class. You will need to pass a string containing the name of your cooperating SMTP server to the constructor. You should be able to find that name in the settings for your normal email client program.

	SmtpClient smtp = 
                      new SmtpClient("YourSmtpServer.com");

Next, the servlet invokes the from() method to specify the originator of the message.

In most cases, this address will need to agree with the specification of the SMTP server above. Because of the large problem with electronic junk mail, many SMTP servers no longer accept and forward messages from unknown senders. If you get an error message to the effect that the server doesn't relay messages, that is your clue that you don't have a proper match here.

	smtp.from("baldwin.richard@iname.com");

Next, the servlet invokes the to() method to specify the addressee or recipient of the message.

	smtp.to("baldwin@austin.cc.tx.us");

Following this, the servlet gets an output stream for the message by invoking the startMessage() method.

	PrintStream msg = smtp.startMessage();

Next the servlet writes the header information and the text for the message into the output stream.

	
    	//Write the message header in the output stream.
    	msg.println("To: baldwin@austin.cc.tx.us");
    	msg.println("Subject: Test Msg from Servlet");
    	msg.println();
    	
    	//Write the text of the message in the output 
        // stream
    	msg.println("This is a test message.");
    	msg.println(new Date());//put date and time in msg

When the servlet has completed writing the message text to the output stream, it closes the output stream and sends the message.

	smtp.closeServer();

After this, the servlet constructs an HTML page and sends it back to the HTML client to notify the client that the message has been sent. You have seen code like this in numerous previous lessons, so I won't repeat it here. However, you can view that code in the full listing of the servlet program in the next section.

Program Listing

A complete listing of the program follows.

/*File Servlet06.java, Copyright 1999, R.G.Baldwin

Rev 3/15/99

The purpose of this program is to illustrate sending email
messages from a servlet.

The servlet constructs and sends an email message 
containing some text along with the current date and time.
The email message produced by one run of the servlet was 
as shown below:
===============	

Subject: Test Msg from Servlet
   Date: Mon, 15 Mar 1999 14:21:21 -0500 (EST)
   From: baldwin.richard@iname.com
     To: baldwin@austin.cc.tx.us

This is a test message.
Mon Mar 15 13:20:05 CST 1999

================
The unsupported class named sun.net.smtp.SmtpClient is
used to send the email message.

After sending the message, the servlet reports back to the
HTML client that activated the servlet that the email
message has been sent.

Tested using the JavaSoft servletrunner program running on
localhost as a substitute for an actual HTTP server.

You must be online to successfully execute this servlet.

Tested using JDK 1.2 and Win95.
**********************************************************/
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import sun.net.smtp.SmtpClient;

public class Servlet06 extends HttpServlet{
  public void doGet(HttpServletRequest req, 
                    HttpServletResponse res)
                      throws ServletException, IOException{
                        
    try {
    	//Pass a string containing the name of your smtp
    	// server as a parameter to the following 
        // constructor
    	SmtpClient smtp = 
                      new SmtpClient("YourSmtpServer.com");
    	
    	//Pass your email address on your smtp server to
        // the following method.
    	smtp.from("baldwin.richard@iname.com");
    	
    	//Pass the email address of the recipient of the 
    	// message to the next method.
    	smtp.to("baldwin@austin.cc.tx.us");

      //Get an output stream for the message
    	PrintStream msg = smtp.startMessage();
    	
    	//Write the message header in the output stream.
    	msg.println("To: baldwin@austin.cc.tx.us");
    	msg.println("Subject: Test Msg from Servlet");
    	msg.println();
    	
    	//Write the text of the message in the output 
        // stream
    	msg.println("This is a test message.");
    	msg.println(new Date());//put date and time in msg

      //Close the stream and send the messaged
    	smtp.closeServer();
    	
    	//Notify HTML client that the message has been sent
      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
    
      out.println("<HTML>");
      out.println("<HEAD><TITLE=Servlet06</TITLE></HEAD>");
      out.println("<BODY>");
    
      out.println("Email message sent<BR>");

      out.println("</BODY></HTML>");
    }catch( Exception e ) {
      e.printStackTrace();
    }//end catch
  }//end doGet()
}//end class Servlet06

-end-