Reading Mails from secure exchange server in Java

Thursday, 26 April 2007, 16:46 | Category : Internet, J2EE, Java, Technology
Tags : , ,

1. Export the certificate for the exchange server from Internet explorer Certificate export wizard e.g. after opening https://webmail.hostname.com, (View certificate >Details > Copy to File). Say the exported file name is certificate.cer

2. Create keystore from the certificate using java keytool (which will create keystore file in current directory). It will ask for a password, give anything (it does not matter)

keytool –import -alias webmail.hostname.com -keystore keystore -file certificate.cer

3. Now While running the Java application pass the VM parameter : –Djavax.net.ssl.trustStore=Path_To_keystoreFile

Sample code to read mail is provided below (Its uses JEC API: http://www.javaexchangeconnector.com/)

import java.text.*;
import java.util.*;
import jec.*;
import jec.dto.*;
public class FetchSecureExchangeMail {
public static void main(String args[]) throws Exception {
ExchangeConnectorFactory factory = new ExchangeConnectorFactory();
ExchangeConnectorInterface connector = factory.createExchangeConnector(“webmail.hostname.com”, “username”,”password”, “Exchange”, true, “[email protected]”);
SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Date sinceDate = dateFormat.parse(“2007-04-25 06:00:00″);
HashSet fromEmailAddressFilter = null;
HashSet toEmailAddressFilter = null;
int maxEmailsReturned = 100;
ArrayList emailsArrayList = connector.getEmails(
sinceDate,
fromEmailAddressFilter,
toEmailAddressFilter,
maxEmailsReturned);
System.out.println(“emailsArrayList.size() : ” + emailsArrayList.size());
if (emailsArrayList.size() > 0) {
ExchangeEmailDTO email1 = (ExchangeEmailDTO) emailsArrayList.get(0);
System.out.println(“email1 email1.getSubject(): ” +
email1.getSubject());
}
}
}