Last active
March 27, 2016 01:03
-
-
Save thorntonrose/ec64d31b88d177aca14c to your computer and use it in GitHub Desktop.
Send mail via SMTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
import java.util.*; | |
import java.text.*; | |
/** | |
* SmtpMailer is used to send mail using SMTP. | |
* | |
* @author Thornton Rose | |
* @version 1.0 | |
*/ | |
public class SmtpMailer { | |
// Fields | |
private static final int SMTP_PORT = 25; | |
private static final char SMTP_ERROR_CODE1 = '4'; | |
private static final char SMTP_ERROR_CODE2 = '5'; | |
protected boolean trace = false; | |
// Methods | |
/** | |
* main() provides a way to test this class from the command line. | |
* | |
*/ | |
public static void main(String[] args) { | |
SmtpMailer mailer; | |
String status; | |
if (args.length != 7) { | |
System.out.println("Usage: SmtpMailer <host> <domain> <sender> <recipients> <content-type> <subject> <text>"); | |
} else { | |
mailer = new SmtpMailer(); | |
mailer.trace = true; | |
status = mailer.send(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); | |
System.out.println("\nStatus: " + status); | |
} | |
} | |
/** | |
* send() sends the mail. | |
* | |
* @param host Host name or IP. | |
* @param domain Sender's domain. | |
* @param sender Sender's address. | |
* @param recipients Recipient addresses. | |
* @param contentType MIME type for mail. | |
* @param subject Subject line. | |
* @param maildata Mail data. | |
* | |
* @return Status message, which will be "OK" if successful. | |
*/ | |
public String send( | |
String host, | |
String domain, | |
String sender, | |
String recipients, | |
String contentType, | |
String subject, | |
String mailtext) { | |
Socket mailSocket; | |
BufferedReader socketIn; | |
DataOutputStream socketOut; | |
String address; | |
StringTokenizer tokenizer; | |
String maildata = ""; | |
String result = "OK"; | |
Date mailDate = new Date(); | |
String formattedMailDate; | |
SimpleDateFormat dateFormatter; | |
// Set the content type. | |
if (! contentType.equals("")) { | |
maildata = maildata + "Content-type: " + contentType + "\n"; | |
} | |
// Build the mail date. | |
// | |
// Example: Fri, 2 Jul 1999 12:49:01 PDT | |
dateFormatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm zzz"); | |
formattedMailDate = dateFormatter.format(mailDate); | |
// Add the date and the rest of the fields. | |
maildata = maildata + | |
"Date: " + formattedMailDate + "\r\n" + | |
"From: " + sender + "\r\n" + | |
"To: " + recipients + "\r\n" + | |
"Subject: " + subject + "\r\n" + | |
"\r\n" + | |
mailtext + "\r\n"; | |
try { | |
// Open the connection to the SMTP server. | |
mailSocket = new Socket(host, SMTP_PORT); | |
try { | |
// Get the input and output streams. | |
socketIn = new BufferedReader( | |
new InputStreamReader(mailSocket.getInputStream()) ); | |
socketOut = new DataOutputStream(mailSocket.getOutputStream()); | |
// Get the initial reply from the server. | |
readReply(socketIn); | |
// Greet the server. | |
sendCommand(socketOut, "HELO " + domain); | |
readReply(socketIn); | |
// Send the sender's address. | |
sendCommand(socketOut, "MAIL FROM: " + sender); | |
readReply(socketIn); | |
// Send the list of recipients. | |
tokenizer = new StringTokenizer(recipients, ","); | |
while (tokenizer.hasMoreElements()) { | |
sendCommand(socketOut, "RCPT TO: " + tokenizer.nextToken()); | |
readReply(socketIn); | |
} | |
// Start the data section. | |
sendCommand(socketOut, "DATA"); | |
readReply(socketIn); | |
// Send the mail message. | |
sendCommand(socketOut, maildata + "."); | |
readReply(socketIn); | |
// End the session. | |
sendCommand(socketOut, "QUIT"); | |
readReply(socketIn); | |
} finally { | |
mailSocket.close(); | |
} | |
} catch(Exception theException) { | |
result = theException.toString(); | |
} | |
return result; | |
} | |
/** | |
* sendCommand() sends an SMTP command to the SMTP server. An | |
* SMTP command is a string that look like: | |
* <pre> | |
* [key words] [data][CR][LF] | |
* </pre> | |
* | |
* <p>Example: <pre>HELO xyz.com</pre> | |
* | |
* @param out The output stream to which to write the command. | |
* @param command The command to write. | |
* | |
* @exception IOException No special handling is done; the exception is | |
* passed back up the call chain. | |
*/ | |
private void sendCommand(DataOutputStream out, String command) | |
throws IOException { | |
out.writeBytes(command + "\r\n"); | |
if (trace) { | |
System.out.println(command); | |
} | |
} | |
/** | |
* readReply() reads the reply from the SMTP server. | |
* | |
* @param reader The input reader from which to read the reply. | |
* | |
* @exception IOException If an IOException occurs because of an error | |
* with socket IO, no special handling is done, and the exception is | |
* passed back up the call chain. If the status code in the reply from | |
* the SMTP server is equal to SMTP_ERROR_CODE1 or SMTP_ERROR_CODE2, an | |
* IOException containing "SMTP: <reply>" is thrown. | |
*/ | |
private void readReply(BufferedReader reader) | |
throws IOException { | |
String reply; | |
char statusCode; | |
reply = reader.readLine(); | |
statusCode = reply.charAt(0); | |
if (trace) { | |
System.out.println(reply); | |
} | |
if ( (statusCode == SMTP_ERROR_CODE1) | | |
(statusCode == SMTP_ERROR_CODE2) ) { | |
throw (new IOException("SMTP: " + reply)); | |
} | |
} | |
} // end SmtpMailer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment