SMTP Implementation with SSL/TLS
There are many ways to implement in java, But mostly used are javax.mail api provided by java and apache commons-net jar.
I personally preferred commons-net over java API as it simplify the implementation as it builds on java api. (see below link)
Only Difference between Simple mail and TLS mail is to provide encrypted channel between to sender-server to mail-serverCommons-net Implementation of SMTP with TLS
public class CommonsNetSMTP {
//Mail-Server
public static final String SMTP_SERVER_ADDRESS = "mail-server";
// SSL/TLS Port; can be different according to server
public static final int SMTP_PORT = 587;
// Sender Mail-Address
public static final String FROM = "from@domain.com";
// Receiver Mail-Address
public static final String TO = "to@domain.com";
// Subject of email
public static final String SUBJECT = "subject";
// Body of email
public static final String BODY = "body";
// Log-writer for checking if something is wrong
public static final PrintWriter COMMAND_LOG_WRITER = new PrintWriter(System.out);
public static void main(String[] args) throws Exception {
// Connect
SMTPSClient client = new SMTPSClient();
client.addProtocolCommandListener(new PrintCommandListener(COMMAND_LOG_WRITER, true));
client.connect(SMTP_SERVER_ADDRESS, SMTP_PORT);
if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
client.disconnect();
System.err.println("SMTP server refused connection.");
return;
}
// Login and Start TLS
client.login();
client.execTLS();
client.helo(InetAddress.getLocalHost().getHostAddress()); // DOES NOT WORK WITH EXCHANGE WITHOUT THIS
// Send Message
client.setSender(FROM);
client.addRecipient(TO);
Writer writer = client.sendMessageData();
SimpleSMTPHeader header = new SimpleSMTPHeader(FROM, TO, SUBJECT);
writer.write(header.toString());
writer.write(BODY);
writer.close();
client.completePendingCommand();
// Logout and Disconnect
client.logout();
client.disconnect();
}
private static void sendMessage(SMTPClient client) throws IOException {
Writer writer = client.sendMessageData();
SimpleSMTPHeader header = new SimpleSMTPHeader(FROM, TO, SUBJECT);
writer.write(header.toString());
writer.write(BODY);
writer.close();
client.completePendingCommand();
}
}
commons-net provide different protocol implementation and it is very easy to use.
Download commons-net jar from following link:
http://commons.apache.org/proper/commons-email/download_email.cgi
Thanks and hopefully it will be useful for you.
Comments
Post a Comment