Recent Changes - Search:

Distributed Computing

This website demonstrates using wikis as teaching and learning tool.

The course instructor is also happy to share the teaching materials here with those who find it readable.

Tutorial - Send Mail by Java

Objective: To use Java network API (Application Programming Interface) to communicate with a mail server to send email

Synopsis: Simple Mail Transfer Protocol (SMTP) is the Internet protocol for email transfer across the Internet. One good way to visualize how SMTP works is to do some real interactions with an SMTP server. Java network API provides class Socket for implementing a network client. In this lab exercise, you will look at using Java socket API to connect to a SMTP server and then interact with it to send a simple testing email.


Activity 1: A Test on SMTP

  • What is SMTP?
Simple Mail Transfer Protocol (SMTP) is the protocol for sending email from one server to another. It is also used to send email from a mail client to a mail server. SMTP uses TCP port 25. One good way to visualize SMTP is to do some real interactions with an SMTP server. The following activity will guide you to do this experiment.
  • Use a telnet session to send email
This activity is about how to use a command prompt on Windows XP to connect to an SMTP server and communicate with it about sending an email message. Please follow the steps below carefully.
To do the following activity, you need to know the hostname of an SMTP server that you can access from your computer. You can find the information from your mail client (also know Mail User Agent) such as Microsoft Outlook Express. The information can be found by checking the value in "Outgoing mail (SMTP)" within the account setting.
In the following description, smtp.ouhk.edu.hk will be used as the SMTP server for demonstration purpose.
There are three steps to SMTP mail transactions. The first step is the sending of the MAIL FROM and RCPT TO messages by the sender, which give the sender's identification and the receiver's information. The second step is sending the DATA message, which gives the mail data. The last step is confirming the transaction by sending the end of mail data indicator.
  • Steps
Step 1. Open a command prompt on Windows XP and type:
      telnet smtp.ouhk.edu.hk 25
You should receive a response message from the server. For example, I received the following:
      220 ouhk.edu.hk ESMTP Sendmail 8.11.1/8.11.1;
      Fri, 30 Sep 2005 17:43:23 +0800 (HKT)
Step 2. Type MAIL FROM: followed by your email address. For example, I entered the following:
      MAIL FROM: andy@ouhk.edu.hk
Step 3. You should receive a response message from the server. I received the following message:
      250 2.1.0 andy@ouhk.edu.hk... Sender ok
Step 4. Type RCPT TO: followed by an email address that you can access for later verification purposes. For example, I entered the following:
      RCPT TO: betty@stevenchoy.com
Step 5. You should receive a response message from the server. I received the following message:
      250 2.1.5 betty@stevenchoy.com... Recipient ok
Step 6. Type DATA as shown in the following.
      DATA
Step 7. You should then receive a response message from the server similar to the following:
      354 Enter mail, end with "." on a line by itself
Step 8. Type the message you want to send for testing. Press the "return" key when you finish a line. Finally, type "." to tell the server that is the end of the message. (A new line containing only "." means the end of the message body.) The following is what I entered in my testing:
      This is the first line of testing message.
      This is the second line of testing message.
      .
Step 9. The server should respond with some appropriate message like the following.
      250 2.0.0 j8U9hrH01679 Message accepted for delivery
Step 10. Type QUIT to close the connection with the SMTP server.
  • Checking
Finally, use your mail client program to log in to the receipt email account and fetch the testing email. This is to verify that what you have done from the above steps has been successful.

Activity 2: to understand what sockets are

  • What are Sockets?
A socket is one end-point of a two-way communication link between two programs running on the network. Therefore, two sockets form the connection between a client program and a server program. In the machine level, a socket is defined as "an IP address plus a port on that computer." When a socket is tied with another socket to form a communication channel, it will also be bounded with the remote IP address plus a port on that remote computer.
  • An Example
For example, when you use a web browser to retrieve a web page for viewing, your computer creates a socket. The socket binds to the IP address of your computer plus a local port number to identify itself to the server. The local port number is usually assigned by the operating system. In the server side of connection, the server that hosts the web page creates another socket. That socket is bound to the IP address of the server machine plus the TCP port 80 for the web protocol HTTP. That socket also has its remote endpoint set to the address and port of the socket in your computer.
To help you visualize the above concept, try the following activity:
Step 1. Go to the following website that provides detailed information about your TCP connection with its web server.
Step 2. Check the following values from the web page: source IP (IP address of your computer), destination IP (IP address of the server), source port (local port number assigned by your computer), and destination port (It is 80 for HTTP). For example, I get the following from it:
      Source IP: 202.40.219.247
      Destination IP: 66.36.247.82
      Source Port: 36853
      Destination Port: 80
Step 3. Use the refresh button of your browser to reload the current web page. Observe the change in the source port number.
  • Another Example
Now, let's use a mail client and a mail server to illustrate the concept of network sockets. The following diagram is helpful for illustrating the detailed descriptions.
A SMTP server uses a socket to wait for client connections. First of all, a server socket is created and bound to the TCP port number 25 for the service of SMTP. The server socket is used only for listening to and then accepting client connections. It is not used for later communication with the connected client; an additional socket, we call it a client socket, is created and used instead to deal with the client.
On the client side, the client must know the hostname or the IP address of the machine on which the target server is running and the port number to which the server is listening. To connect to the server, the client first initiates a connection request by specifying the server's machine and port. Of course, there must be a server running on the specified machine and listening on the specified port, or the client connection attempt will fail (see mark (1) in the figure).
Upon acceptance by the server, the client successfully creates its own socket for communication (see mark (2) in the figure). Note that the client is automatically assigned a port number local to the machine on which the client is running. The programmer needs not specify the client's local port number. A free port will be automatically allocated to the client, if it is not specified earlier.
On the server side a socket is also created. This socket is bound to the local port number to which the server is listening as well as the remote port number of the client's socket (see mark (3) in the diagram).
After that, an input stream and an output stream can be established on both the client side and the server side. The client and server can now communicate by writing to or reading from their sockets (see marks (4) and (5) in the figure).

Activity 3: To understand Java Socket API

  • Introduction
Java network API provides two main classes for implementing client/server networking with TCP/IP. They are classes Socket and ServerSocket. The class Socket represents a TCP connection to a particular host. It is also used to establish input and output streams that are attached to that host. The class ServerSocket is the mechanism by which a server program can listen to and accept connections from clients across a network. In general, both ServerSocket and Socket are used in implementing servers, while in implementing clients only Socket will be used.
  • Using class Socket
The basic procedure of using class Socket to build a client can be summarized as follows:
Step 1. Open a local socket with the following Java statement. You must specify the host name (or the IP address) and the port number of the target server.
      Socket(String host, int port);
Step 2. Your attempt is successful when the target server accepts your connection request. Once you create a Socket object, you use that object's two methods, getInputStream() and getOutputStream(), to establish input stream and output streams to the socket. These two streams enable you to transmit and receive data between the client and the server.
Step 3. Read from and write to the streams according to the application level protocol of the target server. This step will differ from client to client, depending on the server.
Step 4. Close the streams.
Step 5. Close the Socket.

Activity 4: To send email by Java

  • Introduction
Let's now write a simple Java program to send email. We will look at using Java socket (i.e. class Socket) to connect to a SMTP server and then interact with it to send a simple email for testing.
Specifically, all we are going to do is open a local Socket connected to port 25 on some host that is running a SMTP service. If we speak the mail protocol correctly, it will listen to what we say, and send the email for us.
  • The Souce Code
The following is the source code of a Java program that sends a very short email.
import java.io.*;
import java.net.*;

public class TestSendMail {

  public static void main(String args[]) throws IOException {

     Socket socket;
     DataInputStream dataInput;
     PrintStream dataOutput;

     String mailServer = new String("smtp.stevenchoy.com");

     socket = new Socket(mailServer, 25);
     dataInput = new DataInputStream( socket.getInputStream());
     dataOutput = new PrintStream( socket.getOutputStream());

     String sender= "andy@stevenchoy.com";
     dataOutput.println("MAIL FROM: " + sender );
     System.out.println( dataInput.readLine() );

     String addressee= "betty@stevenchoy.com";
     dataOutput.println("RCPT TO: " + addressee );
     System.out.println( dataInput.readLine() );

     dataOutput.println("DATA");
     System.out.println( dataInput.readLine() );

     dataOutput.println("This is the first line of testing message.");
     dataOutput.println("This is the second line of testing message.");
     dataOutput.println(".");
     System.out.println( dataInput.readLine() );

     dataOutput.flush();
     socket.close();
   }
}
  • Explanation of the program
      socket = new Socket(mailServer, 25);
Open a socket and specify the host name and the port number (port 25) of a SMTP server.
      dataInput = new DataInputStream( socket.getInputStream());
      dataOutput = new PrintStream( socket.getOutputStream());
Establish input and output streams to the socket. We use the class DataInputStream for the input stream and the class PrintStream for the output stream.
Start communicating with the SMTP server by reading from and writing to the streams according to the SMTP protocol that has been described before.
      dataOutput.flush();
      socket.close();
Force the data transmission of the streams and close the socket.

Summary

In this tutorial, you first use a telnet session to send email. This gives you a hands-on experience to interact with a mail server to send email. Second, you read some materials and do some activities to understand more about network sockets. After that, you take a closer look at how Java socket API is used to build an Internet client. Finally, you write, compile, and run a simple Java program that uses Java socket to connect to a SMTP server and then interact with it to send a simple email for testing.

Question to think about

SMTP is used to transmit email across the Internet. This tutorial exercise has allowed you to experience that SMTP is a relatively simple and text-based protocol. It is quite easy to talk to an SMTP server to send mails using the telnet program.
Do you think that you can use the telnet program to send mails with non-text elements such as images?

Extra materials for probing further

Your contribution is appreciated!
Edit - History - Print - Recent Changes - Search
Page last modified on September 14, 2007, at 04:36 PM