|
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...
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 bold 220 server.somewhere.com ESMTP Wed, 01 Mar 2006 HELO localhost.localdomain 250 server.somewhere.com Hello root at localhost MAIL FROM:
This e-mail address is being protected from spam bots, you need JavaScript enabled to view it
250 OK RCPT to:
This e-mail address is being protected from spam bots, you need JavaScript enabled to view it
250 Accepted DATA 354 Enter message, ending with "." on a line by itself Subject: Test Email From Ded 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 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. private static void read(BufferedReader br) throws IOException { int c; while ((c = br.read()) != -1) { System.out.print((char) c); if (c == '\n') break; } }
------------------------------------------------------------------------------------------------------------ -----------------------------------------COMPLETE EXAMPLE--------------------------------------------- ------------------------------------------------------------------------------------------------------------ import java.io.*; import java.net.Socket;
/** * Simple SMTP Client that allows your Java App send emails. * Uses Java Sockets to connect directly to an SMTP server. * It supports sending of plain text or HTML emails. * Bonus: Unlike many other Java SMTP Sockets examples, this one actually works. * * @author Olly Oechsle, www.intelligent-web.co.uk */ public class Emailer {
public static void main(String[] args) throws Exception { String results = send("localhost", 25, "
This e-mail address is being protected from spam bots, you need JavaScript enabled to view it
", "
This e-mail address is being protected from spam bots, you need JavaScript enabled to view it
", "Test Email", "<b>You got mail!</b>"); System.out.println(results); }
/** * Sends an email. * * @return The full SMTP conversation as a string. */ public static String send( String host, int port, String to, String from, String subject, String message) throws Exception {
// Save the SMTP conversation into this buffer (for debugging if necessary) StringBuffer buffer = new StringBuffer();
try {
// Connect to the SMTP server running on the local machine. Usually this is SendMail 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())));
try {
// Read the server's hello message read(input, buffer);
// Say hello to the server send(output, "HELO localhost.localdomain\r\n", buffer); read(input, buffer);
// Who is sending the email send(output, "MAIL FROM: " + from + "\r\n", buffer); read(input, buffer);
// Where the mail is going send(output, "RCPT to: " + to + "\r\n", buffer); read(input, buffer);
// Start the message send(output, "DATA\r\n", buffer); read(input, buffer);
// Set the subject send(output, "Subject: " + subject + "\r\n", buffer);
// If we detect HTML in the message, set the content type so it displays // properly in the recipient's email client. if (message.indexOf("<") == -1) { send(output, "Content-type: text/plain; charset=\"us-ascii\"\r\n", buffer); } else { send(output, "Content-type: text/html; charset=\"us-ascii\"\r\n", buffer); }
// Send the message send(output, message, buffer);
// Finish the message send(output, "\r\n.\r\n", buffer); read(input, buffer);
// Close the socket smtpSocket.close();
} catch (IOException e) { System.out.println("Cannot send email as an error occurred."); } } catch (Exception e) { System.out.println("Host unknown"); }
return buffer.toString();
}
/** * Sends a message to the server using the DataOutputStream's writeBytes() method. * Saves what was sent to the buffer so we can record the conversation. */ private static void send(DataOutputStream output, String data, StringBuffer buffer) throws IOException { output.writeBytes(data); buffer.append(data); }
/** * Reads a line from the server and adds it onto the conversation buffer. */ private static void read(BufferedReader br, StringBuffer buffer) throws IOException { int c; while ((c = br.read()) != -1) { buffer.append((char) c); if (c == '\n') { break; } } }
}
|