SMTP Client using Java SocketsIn 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.
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 SocketsConnecting to a socket in Java is relatively easy:
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
You must remember the
Reading Responses from the ServerAs 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.
That is pretty much it, the rest is simply filling in the gaps. |