How to send email with Java with SSL to Exchange Server or GMail

      Comments Off on How to send email with Java with SSL to Exchange Server or GMail

java_rules_liteAgo 3 weeks i need to test for java developers some codes for Email sending via Exchange 2007 with using SSL protocols and authentication. The testing become programing, because the existing code is only enough for default SMTP port (25) without authentication.

Finally i decide to write the code to work with both Gmail  Servers and Exchange 2007.

Before i put the code some tips:

1. I use JavaMail API ( – this is the client requirements

2. For develop i use NetBeans and re imported the code in Eclipse.

3. The sending Email via Exchange with SSL – SMTP its works only if you have a VALID CERTIFICATE. With a self signed certificate is another story.

4. For you test example i tested the code with the Gmail and of course Exchange 2007.

5. The code is very simple, if you are know some java.

6. Note: the uncommented line is for Exchange 2007 settings

7. Note: the Eclipse project contains the JavaMail Api in the LIB directory.

8. You can download from here the projects for  Eclipse SMTP-Exchange-eclipseNetbeans SMTP-Exchange

Lets see:

[code lang=”java”]
package smtpexchange;

import javax.mail.Authenticator;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.PasswordAuthentication;
import java.util.Properties;

* @author veres.levente
* @email:

public class Main {

* @param args the command line arguments

public static void main(String[] args) {
Main m = new Main();

String user_auth = “”;
String user_password = “*****”;
String host=””;
String port = “465”;

// String user_auth = “”;
// String user_password = “*******”;
// String host=”exchange.codespring.local”;
// String port = “25”;

public void SendMail() {

//String from = “”;
String from = “”;
String to = “”;
String Subject = “Hello Word”;
String MessageText = “Exchange Test mail”;

Properties mailProp = new Properties();
* It’s Comming the TLS settings

// Optional debug
mailProp.put(“mail.debug”, “true”);

try {
* Now comming the Real Authentication via the Autheticator Class,
off course i need to overwrite
Authenticator myAuth = new MyAuthenticator();
Session session = Session.getDefaultInstance(mailProp,myAuth);

// Session Debug ON

MimeMessage mymsg = new MimeMessage(session);
mymsg.setFrom(new InternetAddress(from));
mymsg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

} catch (Exception e){

private class MyAuthenticator extends javax.mail.Authenticator{
public PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(user_auth, user_password);