SMTP Client using Java Sockets

In this example we'll present a useful Java Sockets application - sending email in Java by using sockets to connect to an SMTP server.

Sockets are a low level means to connect your Java application to other applications across a network. Read more about sockets on Sun's Java Tutorial

Simple SMTP Example

Emails are sent using the SMTP protocol which is a set of rules for how to ask an SMTP server to send an email for you across the Internet. We won't go into detail about the SMTP protocol, except to show you a basic example.

The following is a simple "conversation" with an SMTP client, the kind of which your email client (Outlook/Thunderbird etc) will have with your ISPs email server each time you click "Send". Your commands are typed in green

220 server.somewhere.com ESMTP Wed, 01 Mar 2006
HELO localhost.localdomain
250 server.somewhere.com Hello root at localhost
MAIL FROM: olly@somewhere.com
250 OK
RCPT to: elvis.presley@hotmail.com
250 Accepted
DATA
354 Enter message, ending with "." on a line by itself
Subject: Test Email From Server
Content-type: text/html; charset="us-ascii"
This is the message! .

250 OK id=1FYJBb-0008VE-5u

You can try this out for yourself if you telnet to your server on port 25 (the port used by SMTP).

The basic jist of the conversation above is that the sender must greet the server with the HELO command, and then say who the mail is from (MAIL FROM:) and where it is going (RCPT to:). The DATA command tells the server that what is coming next is the rest of the email message. The email is completed with a dot (.) on a line on its own.

What we need to do is do a similar thing in Java: send messages to the SMTP server and in each case read the response. Most SMTP servers will expect the response to be read before allowing you to enter the next command. If you don't bother to read the response the SMTP server may respond with a "554 - SMTP Synchronization Error" and refuse to send your email.

Java Sockets

Connecting to a socket in Java is relatively easy:


// Connect to the SMTP server running on the local machine. 
// On Unix systems this is usually SendMail by default
Socket smtpSocket = new Socket(host, port);

// We send commands TO the server with this
DataOutputStream output =
		new DataOutputStream(smtpSocket.getOutputStream());

// And recieve responses FROM the server with this
BufferedReader input =
		new BufferedReader(
		new InputStreamReader(
		new DataInputStream(smtpSocket.getInputStream())));

The example above makes a connection to the socket and then creates a reader and writer with which we can communicate with the server

Sending Commands to the Server

Sending commands to the server is very simple. We just use the writeBytes() function of the DataOutputStream:

output.writeBytes("HELO localhost.localdomain\r\n");

You must remember the \r\n to enter a carriage return after the command otherwise your code will not work!

Reading Responses from the Server

As we've already mentioned, the server expects you to read it's response to each command, otherwise it may refuse to send your email. Hence, after each command we need to call this function.

private static void read(BufferedReader br) throws IOException {
	int c;
	while ((c = br.read()) != -1) {
		System.out.print((char) c);
		if (c == '\n') break;
	}
}

That is pretty much it, the rest is simply filling in the gaps.
View the source code here
Download a working Web Form that uses the Emailer

Back to tutorials