Blog - JServlet.com

To content | To menu | To search

Thursday 3 January 2008

How to use Javamail-Crypto with S/MIME provider

How to use Javamail-Crypto with S/MIME provider :

Needs :

Lasted Api Javamail-Crypto :
http://javamail-crypto.sourceforge.net/

- javamail-crypto_060622.jar
- javamail-crypto-bouncycastle-smime_060622.jar

Install this Jars in Classpath of your application.

There are currently two providers available : one for S/MIME using the BouncyCastle provider,
and one for OpenPGP based on the Cryptix provider.

----

Lasted Api Bouncy Castle (for me Jdk1.4) :
http://www.bouncycastle.org/latest_releases.html

- bcmail-jdk14-138.jar
- bcprov-jdk14-138.jar

Install this Jars in your Classpath of your application.

----

WARNING:

If you have a exception like : java.lang.SecurityException: Unsupported keysize or algorithm parameters,
You need lasted Api Java Cryptography Extension (JCE) with Unlimited Strength Jurisdiction Policy Files (for me Jsdk1.4) :
http://java.sun.com/j2se/1.4.2/download.html (see end of page "Other Downloads")

Due to import control restrictions, the version of JCE policy files that
are bundled in the J2SDK, v 1.4.2 environment allow "strong" but
limited cryptography to be used. This download bundle provides "unlimited strength"
policy files which contain no restrictions on cryptographic strengths.

Install Jars file in jce_policy-1_4_2.zip inside the JRE (for me \j2sdk1.4.x_xx\jre\lib\security), two Jars :
- local_policy.jar
- US_export_policy.jar

----

We need to import (test validity) your certificate .p12 in your JRE :
(here certificate come from "Thawte Personal Freemail Issuing CA")

$>keytool -v -list -keystore personnal.p12 -storetype pkcs12
Enter keystore password:  *******

Keystore type: pkcs12
Keystore provider: SunJSSE

Your keystore contains 1 entry

Alias name: thawte freemail member's thawte consulting (pty) ltd. id
Creation date: 02-Jan-2008
Entry type: keyEntry
Certificate chain length: 3
Certificate[1]:
Owner: EMAILADDRESS=xxx@xxx.fr, CN=Thawte Freemail Member
Issuer: CN=Thawte Personal Freemail Issuing CA, O=Thawte Consulting (Pty) Ltd., C=ZA
Serial number: ce845
Valid from: Sun Aug 22 11:54:25 CEST 2004 until: Mon Aug 22 11:54:25 CEST 2005
Certificate fingerprints:
         MD5:  F0:E6:03:8F:3A:E6:40:26:CE:A8:3D:EE:FB:2E:3F:4D
         SHA1: 04:B4:B4:E1:24:DE:39:14:74:D1:15:45:51:7F:DD:9F:56:05:BE:AE
Certificate[2]:
Owner: CN=Thawte Personal Freemail Issuing CA, O=Thawte Consulting (Pty) Ltd., C=ZA
Issuer: EMAILADDRESS=personal-freemail@thawte.com, CN=Thawte Personal Freemail CA, OU=Certification Services Division, O
=Thawte Consulting, L=Cape Town, ST=Western Cape, C=ZA
Serial number: d
Valid from: Thu Jul 17 02:00:00 CEST 2003 until: Wed Jul 17 01:59:59 CEST 2013
Certificate fingerprints:
         MD5:  7C:B3:90:05:05:EF:D7:BB:DC:BF:30:32:F9:5E:D3:F0
         SHA1: BC:F0:3A:B1:BD:9A:08:9B:EB:46:8D:AF:99:47:5E:83:18:39:99:0F
Certificate[3]:
Owner: EMAILADDRESS=personal-freemail@thawte.com, CN=Thawte Personal Freemail CA, OU=Certification Services Division, O=
Thawte Consulting, L=Cape Town, ST=Western Cape, C=ZA
Issuer: EMAILADDRESS=personal-freemail@thawte.com, CN=Thawte Personal Freemail CA, OU=Certification Services Division, O
=Thawte Consulting, L=Cape Town, ST=Western Cape, C=ZA
Serial number: 0
Valid from: Mon Jan 01 01:00:00 CET 1996 until: Fri Jan 01 00:59:59 CET 2021
Certificate fingerprints:
         MD5:  1E:74:C3:86:3C:0C:35:C5:3E:C2:7F:EF:3C:AA:3C:D9
         SHA1: 20:99:00:B6:3D:95:57:28:14:0C:D1:36:22:D8:C6:87:A4:EB:00:85

----
    
Here simple example of encrypted mail with pk12 public key (see Object Pop3.java & EMail.java) :
    
[...]

import net.suberic.crypto.EncryptionKeyManager;
import net.suberic.crypto.EncryptionManager;
import net.suberic.crypto.EncryptionUtils;

[...]

/**
 * Méthode sendEncryptedMail, envoie un mail simple encrypté par une clé public.
 *
 * @param _from         Adresse de départ
 * @param _to             Adresse du destinataire
 * @param _subject         Sujet du mail
 * @param _msg             Corps du message (simple texte)
 * @param _filepk12     Objet File .p12
 * @param _smimePw         keystore password
 * @param _alias         Nom convivial du certificat (Alias name)
 *
 * @exception            Exception Si une erreur survient.
 */
public void sendEncryptedMail(String _from, String _to, String _subject, String _msg, File _filepk12, String _smimePw, String _alias)
throws Exception
{
    // Get session
    session = Session.getInstance((Properties) getSessionProperties(), null);

    // debug ?
    session.setDebug(debug);

    // Define message
    MimeMessage message = new MimeMessage(session);

    try
    {
        
        StringTokenizer b_stk = new StringTokenizer(_from, ",;");
        while (b_stk.hasMoreTokens())
        {
            message.setFrom(new InternetAddress(b_stk.nextToken()));
            break;
        }

        StringTokenizer a_stk = new StringTokenizer(_to, ",;");
        while (a_stk.hasMoreTokens())
        {
            addToAddress(a_stk.nextToken());
        }
        //message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));

        for (int i = 0; i < a_destinationTO.size(); i++)
            message.addRecipient(Message.RecipientType.TO, (Address) a_destinationTO.elementAt(i));
        for (int i = 0; i < a_destinationCC.size(); i++)
            message.addRecipient(Message.RecipientType.CC, (Address) a_destinationCC.elementAt(i));
        for (int i = 0; i < a_destinationBCC.size(); i++)
            message.addRecipient(Message.RecipientType.BCC, (Address) a_destinationBCC.elementAt(i));
        if (m_addressReply != null)
            message.setReplyTo(m_addressReply);

        message.addHeaderLine("X-Priority: " + s_priorities[m_Priority]);
        Calendar c = Calendar.getInstance(Locale.FRANCE);
        message.setSentDate(c.getTime());
        message.setSubject(_subject, charset);
        message.setText(_msg, charset);

        message.saveChanges(); // don't forget this
        
        // get the S/MIME EncryptionUtilities
        EncryptionUtils smimeUtils = EncryptionManager.getEncryptionUtils(EncryptionManager.SMIME);
          
        // load the S/MIME keystore from the given file.
        char[] smimePw = new String(_smimePw).toCharArray();
        EncryptionKeyManager smimeKeyMgr = smimeUtils.createKeyManager();
        smimeKeyMgr.loadPublicKeystore(new FileInputStream(_filepk12), smimePw);
        
        // get the S/MIME public key for encryption
        java.security.Key smimeKey = smimeKeyMgr.getPublicKey(_alias);
        
        // encrypt the message
        MimeMessage smimeEncryptedMsg = smimeUtils.encryptMessage(session, message, smimeKey);
        
        if (user != null && pass != null)
        {
            // Send message with authentification!
            Transport tr = session.getTransport("smtp");
            tr.connect(MailHost, user, pass);
            smimeEncryptedMsg.saveChanges(); // don't forget this
            tr.sendMessage(smimeEncryptedMsg, smimeEncryptedMsg.getAllRecipients());
            tr.close();
        }
        else
        {
            // Send message
            Transport.send(smimeEncryptedMsg);
        }
    }
    catch (AddressException ae)
    {
        throw new Exception("EMail.sendEncryptedMail Error : " + ae);
        //System.out.println(ae);
    }
    catch (MessagingException me)
    {
        throw new Exception("EMail.sendEncryptedMail Error : " + me);
        //System.out.println(me);
    }
}

----

Here simple example for decrypt mail with pk12 private key :

/**
* Méthode ReadEncryptedMessage, récupère un S/MIME Encrypted Message
*
* @param pop_message         Objet MimeMessage à décoder...
* @param _filepk12             Objet File .p12
* @param _smimePw             keystore password
* @param _alias                 Nom convivial du certificat (Alias name)
* @return MimeMessage        Retourne un MimeMessage décrypté
*/
public static MimeMessage ReadEncryptedMessage(MimeMessage pop_message, File _filepk12, String _smimePw, String _alias)
throws Exception
{
    String cryptotype = EncryptionManager.checkEncryptionType(pop_message);
    EncryptionUtils cryptoUtils = EncryptionManager.getEncryptionUtils(cryptotype);
    
    EncryptionKeyManager keyMgr = cryptoUtils.createKeyManager();
    char[] smimePw = new String(_smimePw).toCharArray();
        
    keyMgr.loadPrivateKeystore(new FileInputStream(_filepk12), smimePw);
    
    MimeMessage decryptedMsg = null;
      
    Key privateKey = keyMgr.getPrivateKey(_alias, smimePw);
    try
    {
        decryptedMsg = cryptoUtils.decryptMessage(null, pop_message, privateKey);
    }
    catch (Exception e)
    {
        Object o = pop_message.getContent();
        System.err.println("msg.getContent() = " + o + ", a " + o.getClass().getName());
        System.err.println("error decrypting message with key " + privateKey + ":  " + e);
        e.printStackTrace();
    }

    return decryptedMsg;
}

----

Here simple example for signed mail with pk12 private key :

/**
 * Méthode sendSignedMail, envoie un mail simple signé par une clé privée.
 *
 * @param _from         Adresse de départ
 * @param _to             Adresse du destinataire
 * @param _subject         Sujet du mail
 * @param _msg             Corps du message (simple texte)
 * @param _filepk12     Objet File .p12
 * @param _smimePw         keystore password
 * @param _alias         Nom convivial du certificat (Alias name)
 * @exception            Exception Si une erreur survient.
 */
public void sendSignedMail(String _from, String _to, String _subject, String _msg, File _filepk12, String _smimePw, String _alias)
throws Exception
{
    // Get session
    session = Session.getInstance((Properties) getSessionProperties(), null);

    // debug ?
    session.setDebug(debug);

    // Define message
    MimeMessage message = new MimeMessage(session);

    try
    {
        
        StringTokenizer b_stk = new StringTokenizer(_from, ",;");
        while (b_stk.hasMoreTokens())
        {
            message.setFrom(new InternetAddress(b_stk.nextToken()));
            break;
        }

        StringTokenizer a_stk = new StringTokenizer(_to, ",;");
        while (a_stk.hasMoreTokens())
        {
            addToAddress(a_stk.nextToken());
        }
        //message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));

        for (int i = 0; i < a_destinationTO.size(); i++)
            message.addRecipient(Message.RecipientType.TO, (Address) a_destinationTO.elementAt(i));
        for (int i = 0; i < a_destinationCC.size(); i++)
            message.addRecipient(Message.RecipientType.CC, (Address) a_destinationCC.elementAt(i));
        for (int i = 0; i < a_destinationBCC.size(); i++)
            message.addRecipient(Message.RecipientType.BCC, (Address) a_destinationBCC.elementAt(i));
        if (m_addressReply != null)
            message.setReplyTo(m_addressReply);

        message.addHeaderLine("X-Priority: " + s_priorities[m_Priority]);
        Calendar c = Calendar.getInstance(Locale.FRANCE);
        message.setSentDate(c.getTime());
        message.setSubject(_subject, charset);
        message.setText(_msg, charset);

        message.saveChanges(); // don't forget this
        
        // get the S/MIME EncryptionUtilities
        EncryptionUtils smimeUtils = EncryptionManager.getEncryptionUtils(EncryptionManager.SMIME);
          
        // load the S/MIME keystore from the given file.
        char[] smimePw = new String(_smimePw).toCharArray();
        EncryptionKeyManager smimeKeyMgr = smimeUtils.createKeyManager();
        smimeKeyMgr.loadPrivateKeystore(new FileInputStream(_filepk12), smimePw);
        
        // get our keys.
        java.security.Key smimeKey = smimeKeyMgr.getPrivateKey(_alias, smimePw);
        
        // write smime message.
        MimeMessage smimeSignedMsg = smimeUtils.signMessage(session, message, smimeKey);
       
        if (user != null && pass != null)
        {
            // Send message with authentification!
            Transport tr = session.getTransport("smtp");
            tr.connect(MailHost, user, pass);
            smimeSignedMsg.saveChanges(); // don't forget this
            tr.sendMessage(smimeSignedMsg, smimeSignedMsg.getAllRecipients());
            tr.close();
        }
        else
        {
            // Send message
            Transport.send(smimeSignedMsg);
        }
    }
    catch (AddressException ae)
    {
        throw new Exception("EMail.sendSignedMail Error : " + ae);
        //System.out.println(ae);
    }
    catch (MessagingException me)
    {
        throw new Exception("EMail.sendSignedMail Error : " + me);
        //System.out.println(me);
    }
}


----

Here simple example for check signed mail with pk12 public key :

/**
* Méthode CheckSignedMessage, check un S/MIME Signed Message
*
* @param pop_message         Objet MimeMessage a décodé...
* @param _filepk12             Objet File .p12
* @param _smimePw             keystore password
* @param _alias                 Nom convivial du certificat (Alias name)
* @return boolean            Retourne true si la signature est ok!
* @exception                    Si par exemple le certificat n'est plus valide...
*/
public static boolean CheckSignedMessage(MimeMessage pop_message, File _filepk12, String _smimePw, String _alias)
throws Exception
{
    String cryptotype = EncryptionManager.checkEncryptionType(pop_message);
    EncryptionUtils cryptoUtils = EncryptionManager.getEncryptionUtils(cryptotype);
      
    EncryptionKeyManager keyMgr = cryptoUtils.createKeyManager();
    char[] smimePw = new String(_smimePw).toCharArray();
        
    keyMgr.loadPublicKeystore(new FileInputStream(_filepk12), smimePw);
    
    // good or not ?
    boolean goodSignature = false;
    
    Key publicKey = keyMgr.getPublicKey(_alias);
    cryptoUtils.checkSignature(pop_message, publicKey);
    
    try
    {
        goodSignature = cryptoUtils.checkSignature(pop_message, publicKey);
    }
    catch (Exception e)
    {
        Object o = pop_message.getContent();
        System.err.println("msg.getContent() = " + o + ", a " + o.getClass().getName());
        System.err.println("error decrypting message with key " + publicKey + ":  " + e);
        e.printStackTrace();
    }
    
    return goodSignature;
}

          
(Mmmh... Strange world, we need to hash code for feel free!)

Tuesday 3 July 2007

Object HTMLForm - method post and get URL


Object HTMLForm, accept method post and get URL :
    - Map of parameters
    - Past ACL (Access Control List)
    - Get Cookie

Use external API JCookie :
http://jcookie.sourceforge.net/

Example :

        HTMLForm form = null;
   
        HashMap map = new HashMap();
   
        String url = "https://altern.org/";
              
        // url & method
        map.put("url", url);
        map.put("method", "get");
   
        // ACL conf
        //map.put("user", "user");
        //map.put("password", "password");
       
        // others parameters..
        //map.put("what", "hi!");
       
        try
        {
            form = new HTMLForm(false); // cookie ?
   
            form.setFollowRedirects(true); // redirect ?
            form.setKeepAlive(true);
           
            System.err.println("check : "+HTMLForm.checkURL(map));
            form.setParametersMap(map);
   
            BufferedReader in = new BufferedReader(new InputStreamReader(form.sendFormMessage()));
            System.out.println("HTMLForm : invoking URL "+ url);
   
            StringBuffer page = new StringBuffer();
            String line = null;
            
            while((line = in.readLine()) != null) page.append(line).append("\n");
           
            System.err.println(page.toString());
            System.err.println(">End of line");
           
            CookieJar cookies = form.getCookieJar();
           
            if (cookies != null)
            {
                 System.out.println("cookie size : "+ cookies.size());
               
                Iterator iter = cookies.iterator();
                while(iter.hasNext())
                {
                    Object cookie = iter.next();
                    System.out.println("cookie : "+ cookie);
                }
            }
        }
        catch (Exception e)
        {
            System.out.println(e);
            System.out.println("Pile : ");
            e.printStackTrace();
        }
        finally
        {
            if (form!=null) form.disconnect();
        }

Source : HTMLForm.java
               


Monday 2 July 2007

Object FTP - download and upload file


Object FTP, download and upload file under FTP protocol, accept passive or active mode, SSL communication in test (java 1.5 ssl class)

Compatible with some FTP server  Unix, Windows, JScape server...

UFS format only (Unix File System).

Many people do not make the difference between FTP, FTPS and SFTP, here:
    - FTP  : transfert FTP with basic socket
    - FTPS : transfert FTP with SSL certificat
    - SFTP : transfert with SSH (use command SCP can transfert file like FTP)

Socks proxy parameters :
java -DsocksProxyPort=1080 -DsocksProxyHost=socks.foo.com -Djava.net.socks.username=user01 -Djava.net.socks.password=pass1234 ...

Command FTP allowed :
 ABOR ACCT ALLO CDUP CWD DELE HELP LIST MDTM MKD
 MODE NOOP PASS PASV PORT PWD QUIT REIN REST RETR
 RMD RNFR RNTO SITE SIZE SMNT STAT STOR STRU SYST
 TYPE USER FEAT
 
Command none implemented (not use):
APPE NLST STOU

Port used :
Port 21  --> FTP command port
Port 20 data port
Port 990  --> FTPS command port over TLS/SSL
Port 989 data port

Example :

    FTP m_client = null;
   
    try
    {
        m_client = new FTP("192.168.1.66", 21, System.out); // ftps in test 990
        m_client.setSocketTimeout(5000);                    // set timeout 5s
       
        m_client.setNetworkInterface("eth0");                     // defaut eth0
        m_client.setPassivMode(true);                         // defaut true
        //m_client.setSecureFTP(true);                         // defaut false
       
        // on démarre la session vers le serveur FTP
        m_client.session("test", "test");                
       
        //m_client.mode('S');                            // mode de transfert defaut 'S'
        //m_client.stru('F');                            // structure des fichiers defaut 'F'
       
        System.err.println("*** "+m_client.getWelcome());
        //m_client.cwd("/upload");                        // change dir
       
        // nom du répertoire courant
        System.err.println("---> "+m_client.pwd());
       
        //m_client.help();
        //m_client.system();
        //m_client.stat();
        //m_client.features();
       
        // liste les fichiers dans le répertoire courant ou nommé list("/upload");
        FtpFile a_fl[] = m_client.list();
        for (int i=0; i<a_fl.length; i++)
            System.err.println(((a_fl[i].isFile())? a_fl[i].getName()+" "+(a_fl[i].i_size+" ") : "<"+a_fl[i].getName()+">"));
           
   
        /*
        // début du test   
        try { m_client.dele("testx.pdf"); }
        catch (Exception dele) { }
       
        System.err.println("*** allocate 6000 bytes : "+m_client.allo(6000));

        // ATTENTION taille originale du fichier testx.pdf : 3434 bytes
        m_client.upLoad("D:\\temp\\testx.pdf");
        //m_client.upLoad("D:\\temp\\testx.pdf", 2456);
       
        System.err.println("date modif : "+m_client.modtime("testx.pdf"));
        System.err.println("size : "+m_client.size("testx.pdf"));
       
        m_client.downLoad("testx.pdf", "c:\\temp\\testx.pdf");
        //m_client.downLoad("testx.pdf", "c:\\temp\\testx.pdf", new File("c:\\temp\\testx.pdf").length());
        //m_client.downLoad("testx.pdf", "c:\\temp\\testx.pdf", 2456);
       
        // création répertoire test
        m_client.mkd("test");
        m_client.cwd("/upload/test");   
       
        m_client.upLoad("d:\\temp\\testx.pdf");
       
        // liste des fichiers dans test
        FtpFile b_fl[] = m_client.list();
        for (int i=0; i<b_fl.length; i++)
            System.err.println(((b_fl[i].isFile())? b_fl[i].getName()+" "+b_fl[i].i_size : "<"+b_fl[i].getName()+">"));
       
        // effacement du fichier testx.pdf et répertoire test ...
        m_client.dele("testx.pdf");
        m_client.cwd("/upload");
        //m_client.toParentDir();
        System.err.println("---> "+m_client.pwd());
        m_client.rmd("test");
        */
    }
    catch (Exception e)
    {
        System.err.println("FTP error : "+ e.toString());
        e.printStackTrace();
    }
    finally
    {
        // ferme la connexion au serveur FTP
        m_client.close();
       
        // exit
        System.exit(0);
    }


Source : FTP.java


Sunday 1 July 2007

Object Pop3 - receive mail message with JavaMail API


Object Pop3, receive mail message with JavaMail API, accept protocol POP3, IMAP over SSL.

Sun JavaMail API 1.4 (under GPL v2) : http://java.sun.com/products/javamail/ 
 - mail.jar 1.4 (pop3.jar, smtp.jar, imap.jar, mailapi.jar, dsn.jar)
JAF :  http://java.sun.com/javase/technologies/desktop/javabeans/jaf/index.jsp 
- activation.jar

Some inner class in Pop3 object :

Pop3.Tools : class with useful's methods to parse multipart message 
    - get body / body in html
    - save File
    - File Handle Multipart
    - etc ...

Pop3.FileBinary : class with useful's methods to find extension of file attachment in message
    - file zip, pdf, images...
    - and file like Microsoft Office... word, excel!

SSL explain and example :
We need to put SSL certificat in key store manager inside JRE...

Well see URL : https://altern.org/ with your browser.
And export SSL certificate of site web in file ex : altern.cer

Now import SSL certificate in key store manager :
go in path \j2sdk1.4.x_xx\jre\lib\security\
and use keytool with some options :
$> keytool -import -keystore cacerts -file altern.cer

The password by default of global key store manager is : 'changeit'

Now we can communicate with the domain in POP or SMTP over SSL...

Example :

    //Pop3 pop = new Pop3("c:\\temp", "pop.xxx.fr", "xxxx", "xxxx"); // default pop3!
    Pop3 pop = new Pop3("c:\\temp", "xxxx.org", "xxxx", "xxxx", POPS_PORT, POP);

    pop.setSecurePOP3(true);
    pop.setDebug(true);
    pop.setSocketTimeout(5000);

    try
    {
      System.err.println("Start Job --- Pop3");

      // read eml file (txt)
      /*
      MimeMessage mime_mess = Pop3.Tools.getMimeMessage("c:\\temp\\002b01c7xxxa36c95f0$bb64668a@unixxxip85.eml");

      System.out.println("\tFrom : " + mime_mess.getFrom()[0]);
      System.out.println("\tSubject : " + mime_mess.getSubject());
      System.out.println("\tDate : " + mime_mess.getSentDate());
      Address[] address = mime_mess.getReplyTo();
      System.out.println("\tReplyTo : " + MimeUtility.decodeText(address[0].toString()));

      Vector vec_file_mess = Pop3.Tools.getFile(mime_mess);
      if (!vec_file_mess.isEmpty())
      {
        for (int j=0; j<vec_file_mess.size(); j++)
        {
          String a_file = (String) vec_file_mess.elementAt(j);

          // copier les fichiers hors du dossier temporaire!!!
          System.out.println("\tPathFileName : " + a_file);
        }
      }
      else System.out.println("\tPas de fichier en attachement!");

      // le body
      try
      {
          String body = Pop3.Tools.getBody(mime_mess);
          System.out.println("\n\tBody : " + body);
      }
      catch(Exception e) { System.out.println("\n\tBody : " + e); }

      // body html pour les mail au format html uniquement...
      try
      {
          String bodyhtml = Pop3.Tools.getBodyHtml(mime_mess);
          System.out.println("\n\tBodyHtml: " + bodyhtml);
      }
      catch(Exception e) { System.out.println("\n\tBodyHtml : " + e); }
     */
      // fin lecture d'un fichier eml (texte)

      // POP3 mode : INBOX par defaut
      // IMAP4 mode : INBOX par defaut, dispo normalement : Drafts, Sent, Trash
      Message[] pop_message = pop.getMail(true); //  dossier courant "INBOX", true debug

      /*
      // IMAP4 liste tous les dossiers du folder courant
      //UIDFolder ufolder = (UIDFolder) pop.getFolder();
      //System.err.println("MESSAGE UID :" + ufolder.getUID(pop_message[i]));

      Folder[] xfolders = pop.getRootFolders();
      if (xfolders ==null || xfolders.length == 0) System.err.println("***  IMAP Root Folder : ?? ");
      else
      {
          System.err.println("**** IMAP Root Folder : ");
          for (int i=0, n=xfolders.length; i<n; i++)
              System.err.println("\tFolder : -"+i+" "+xfolders[i].getName());
      }

      // dossier courant
      xfolders = pop.getFolders();
      if (xfolders ==null || xfolders.length == 0) System.err.println("***  NO Folder in current folder!");
      else
      {
          System.err.println("**** Folder : ");
          for (int i=0, n=xfolders.length; i<n; i++)
              System.err.println("\tFolder : -"+i+" "+xfolders[i].getName());
      }

      // change de dossier...
      //pop_message = pop.getMail("Test"+pop.getSep()+"SubTest", true); //  dossier courant "INBOX", true debug
      pop_message = pop.getMail("Test", true); //  dossier courant "INBOX", true debug

      xfolders = pop.getRootFolders();
      if (xfolders ==null || xfolders.length == 0) System.err.println("***  IMAP Root Folder : ?? ");
      else
      {
          System.err.println("**** IMAP Root Folder : ");
          for (int i=0, n=xfolders.length; i<n; i++)
              System.err.println("\tFolder : -"+i+" "+xfolders[i].getName());
      }

      // dossier courant
      xfolders = pop.getFolders();
      if (xfolders ==null || xfolders.length == 0) System.err.println("***  NO Folder in current folder!");
      else
      {
          System.err.println("**** Folder : ");
          for (int i=0, n=xfolders.length; i<n; i++)
              System.err.println("\tFolder : -"+i+" "+xfolders[i].getName());
      }

      Folder[] subcr_folder = pop.getSubscribedFolder();
      if (subcr_folder == null || subcr_folder.length == 0) System.err.println("*** NO Folder Subcribe in current folder!");
      else
      {
          for (int i=0, n=subcr_folder.length; i<n; i++)
              System.err.println("************ Folder Subcribe : -"+i+" "+xfolders[i].getName());
      }

      Folder[] unsubcr_folder = pop.getUnSubscribedFolder();
      if (unsubcr_folder == null || unsubcr_folder.length == 0) System.err.println("*** NO Folder UnSubcribe in current folder!");
      else
      {
          for (int i=0, n=unsubcr_folder.length; i<n; i++)
              System.err.println("************ Folder UnSubcribe : -"+i+" "+xfolders[i].getName());
      }
      */

      // IMAP4 création, copie & destruction (PERMANENT) de dossier
      /*
      System.out.println("*** DELETE FOLDER : "+ pop.deleteFolder("Test"));
      System.out.println("*** CREATE FOLDER : "+ pop.createFolder("Test"));
      System.out.println("*** COPY FOLDER : "+ pop.copyFolderMessages("Trash", "Test"));
      */

      //System.out.println("*** SUBCRIBE/UNSUBCRIBE FOLDER : "+ pop.setSubscribed("Test", false));
      //System.out.println("*** RENAME FOLDER : "+  pop.renameFolder("Test", "Testy"));
      //System.out.println("*** DELETE FOLDER : "+ pop.deleteFolder("Testy"));
      //System.out.println("*** COPY FOLDER : "+ pop.copyFolderMessages("Test", "SubTest"));

      // IMAP4 liste tous les dossiers de Test
      //pop_message = pop.getMail("Test", true); // on change de dossier courant pour root
      //System.out.println("*** CREATE FOLDER : "+ pop.createFolder("Test.SubTest"));
      //System.out.println("*** SUBCRIBE/UNSUBCRIBE FOLDER : "+ pop.setSubscribed("Test.SubTest", true));
      //System.out.println("*** DELETE FOLDER : "+ pop.deleteFolder("Test.SubTest"));


      for (int i=0, n=pop_message.length; i<n; i++)
      {
        //pop_message[i].writeTo(System.out);

          System.err.println("\tFrom : " + pop_message[i].getFrom()[0]);
        System.err.println("\tSubject : " + pop_message[i].getSubject());
        System.err.println("\tDate : " + pop_message[i].getSentDate());
        Address[] add = pop_message[i].getReplyTo();
        System.err.println("\tReplyTo : " + add[0].toString());
        /*
        MimeMessage mess = (MimeMessage) pop_message[i];

        String[] strTo = mess.getHeader("To");
        if (strTo !=null) // ?
          for (int j=0, m=strTo.length; j<m; j++)
            System.out.println("\tTo : " + strTo[j]);

        String[] strReceived = mess.getHeader("Received");
        if (strReceived !=null) // impossible
          for (int j=0, m=strReceived.length; j<m; j++)
            System.out.println("\tReceived : " + strReceived[j]);

        System.out.println("\tMessage-ID : " + mess.getMessageID());


        //Enumeration e = mess.getAllHeaders();
        //while (e.hasMoreElements())
        //{
        //        Header header = (Header) e.nextElement();
        //        System.out.println(header.getName() +" : "+header.getValue());
        //}


        // le body
        try
        {
            String body = Pop3.Tools.getBody(pop_message[i]);
            System.out.println("\n\tBody : " + body);
        }
        catch(Exception e) { System.out.println("\n\tBody : " + e); }


        // body html pour les mail au format html uniquement...
        try
        {
            String bodyhtml = Pop3.Tools.getBodyHtml(pop_message[i]);
            System.out.println("\n\tBodyHtml: " + bodyhtml);
        }
        catch(Exception e) { System.out.println("\n\tBodyHtml : " + e); }

        // les fichiers en attachement..
        Vector vec_file = Pop3.Tools.getFile(pop_message[i]);
        if (!vec_file.isEmpty())
        {
          for (int j=0; j<vec_file.size(); j++)
          {
            String a_file = (String) vec_file.elementAt(j);

            // copier les fichiers hors du dossier temporaire!!!
            System.out.println("\tPathFileName : " + a_file);

            Pop3.FileBinary fb = new Pop3.FileBinary(a_file);
            System.out.println("\t isPdf : " + fb.isPdf());
             System.out.println("\t isMSOffice : " + fb.isMSOffice());

          }
        }
        else System.out.println("\tPas de fichier en attachement!");

        // les fichiers embarqués (dans l'html ou autre...)
        Vector vec_file_embed = Pop3.Tools.getFileEmbed(pop_message[i], "image/jpeg");
        if (!vec_file_embed.isEmpty())
        {
          for (int j=0; j<vec_file_embed.size(); j++)
          {
            String a_file = (String) vec_file_embed.elementAt(j);
            // copier les fichiers hors du dossier temporaire!!!
            System.out.println("\tPathFileName Embed: " + a_file);
          }
        }
        else System.out.println("\tPas de fichier embarqué!");

        System.out.println();

        // lecture des Flags IMAP4
        System.out.println("Count read : "+pop.countMessageRead());
        System.out.println("isNew : "+pop.isNew(i));
        System.out.println("isRead : "+pop.isRead(i));

        // sauve le message dans un répertoire dédié...
        //Pop3.Tools.saveELM(mess, new File("c:\\temp"));

        System.out.println("isConnected : " + pop.store.isConnected()); // Noop

        // on se prepare à effacer les mails!
        //pop_message[i].setFlag(Flags.Flag.DELETED, false); // true
        */

        System.out.println();
        System.out.println();

      }

      System.out.println("End Job --- Pop3");
    }
    catch(Exception e)
    {
      System.out.println(e);
      System.out.println("Pile : ");
      e.printStackTrace();
    }
    finally
    {
      // ferme la session pop3 et efface les messages flagger 'DELETED' !
      try { pop.close(true); } catch (MessagingException me) { }
    }
  }

Source : Pop3.java


Saturday 30 June 2007

Object EMail - send mail with JavaMail API


Object EMail send email with some options, accept protocol SMTP and SMTPS over SSL :

Sun JavaMail API 1.4 (under GPL v2) : http://java.sun.com/products/javamail/ 
 - mail.jar 1.4 (pop3.jar, smtp.jar, imap.jar, mailapi.jar, dsn.jar)
JAF :  http://java.sun.com/javase/technologies/desktop/javabeans/jaf/index.jsp 
- activation.jar

SSL explain and example :
We need to put SSL certificat in key store manager inside JRE...

Well see URL : https://altern.org/ with your browser.
And export SSL certificate of site web in file ex : altern.cer

Now import SSL certificate in key store manager :
go in path \j2sdk1.4.x_xx\jre\lib\security\
and use keytool with some options :
$> keytool -import -keystore cacerts -file altern.cer

The password by default of global key store manager is : 'changeit'

Now we can communicate with the domain in POP or SMTP over SSL...

Example :

        //Pop3 pop = new Pop3("c:\\temp", "pop.xxxx.fr", "xxxx", "xxxx");
        EMail fox = new EMail("smtp.gmail.com"); //smtp.xxx.com

        try
        {
            //Message[] pop_message = pop.getMail(true);

            //for (int i = 0, n = pop_message.length; i < n; i++)
            //{

                // SSL connexion ?
                fox.setSecureSMTP(true); // defaut false
                fox.setPort(465); // gmail 25 (Ok ssl false), 465 (ok SSL true), 587 (Ok ssl false!), default port 25
                fox.setAuthentication("xxxx@gmail.com", "xxxx"); // active l'envoie du mail avec authentification !!!

                fox.setTLS(true); // mandatory for gmail
               
                //fox.setQuitWait(false); // mandatory for gmail
              
                // active le débuggage
                fox.setDebug(true);

                // active l'envoie du mail partiel, si une des adresses emails n'est pas valide!!!
                //fox.setPartial(true);

                // ajouter un destinataire
                //fox.addToAddress("test@xxxx.fr");

                // attacher un destinataire d'adresse de reponse
                //fox.addReplyTo("fox@xxxx.fr");

                // priorité du mail : 0 basse, 1 moyenne, 2 haute
                fox.setPriority(2);

                // envoi du mail
                // ordre des aguments : from, to , subject, body, files
                //fox.sendMail("test@xxxx.fr", "faa@xxxx.fr", "test accents ê ô é è à ù €", "Haloa ê ô é è à ù €!!!");

                fox.setHtml(true);
                fox.setSubject("test coucou");
                fox.setBody("<b>test coucou</b>"); // html true!
                fox.setFrom("xxxx@gmail.com");
                fox.setTo("faa@xxxx.org");
                fox.sendMail();

                // exemple piece jointe
                //fox.sendMail("test@xxxx.fr", "fandriano@xxxx.fr", "test accents ê ô é è à ù €", "Haloa ê ô é è à ù €!!!", "C:\\temp\\date_serial.ser");

                // exemple liste de pieces jointes
                /*
                String[] filesname =
                {
                    "N:\\intranet\\sites\\xxxx\\exp_IMF002_1018622244161.csv",
                    "N:\\intranet\\sites\\xxxx\\exp_IMF001_1018622243801.csv"
                };

                fox.sendMail("test@xxxx.fr", "faa@xxxx.fr", "test", "Haloa !!! ", filesname);
                */

                // exemple forward
                //fox.deleteAllAddress();
                //fox.sendForward("test@xxxx.fr", "faa@xxxx.fr", "ceci est un forward!", pop_message[i]);

                // exemple redirect
                //fox.deleteAllAddress();
                //fox.sendRedirect("test@xxxx.fr", "aa@xxx.fr", pop_message[i]);

                // efface le message du serveur pop3
                //pop_message[i].setFlag(javax.mail.Flags.Flag.DELETED, true);

            //}
        }
        catch (Exception e)
        {
            System.out.println(e);
            e.printStackTrace();
        }
        finally
        {
            // ferme la session pop3 et efface les messages flagger 'DELETED' !
            /* try { pop.close(true); } catch (MessagingException me) { } */
        }


Source :  EMail.java

Friday 29 June 2007

Object NNTP - install NNTP provider with JavaMail API

Well i have installed a NNTP provider from gnu.org :

NEEDS :

- The current stable release of GNU JavaMail is version 1.1.2
http://ftp.gnu.org/gnu/classpathx/mail-1.1.2.tar.gz

- You need also the current versions of GNU JAF and GNU inetlib to build it.
http://ftp.gnu.org/gnu/classpathx/activation-1.1.1.tar.gz
http://ftp.gnu.org/gnu/classpath/inetlib-1.1.1.tar.gz


INSTALL & COMPILE :
Ungzip and make modification on build.xml (only location of install-dir)

inetlib project need 2 jars libs for compile :
javax-security.jar (see http://ftp.gnu.org/gnu/gnu-crypto/gnu-crypto-2.1.0-bin.zip)

jsse.jar (see http://java.sun.com/products/jsse/downloads/index.html)
or build jessie: http://savannah.nongnu.org/projects/jessie/

activation project no need jar!

Well we can compile the gnu mail project with activation.jar, inetlib.jar
Change build.xml only location of install-dir

Two jars file are generated after compile mail-1.1.2 :
- gnumail.jar
- gnumail-providers.jar

(Wow... I like gnu project that depend of 3 others projects and one external archive...)


INSTALL NEW NNTP PROVIDER :

Create a file 'javamail.providers' (see inside mail.jar of JavaMail 1.4 of Sun) :

--
# JavaMail IMAP provider Sun Microsystems, Inc
protocol=imap; type=store; class=com.sun.mail.imap.IMAPStore; vendor=Sun Microsystems, Inc;
protocol=imaps; type=store; class=com.sun.mail.imap.IMAPSSLStore; vendor=Sun Microsystems, Inc;
# JavaMail SMTP provider Sun Microsystems, Inc
protocol=smtp; type=transport; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc;
protocol=smtps; type=transport; class=com.sun.mail.smtp.SMTPSSLTransport; vendor=Sun Microsystems, Inc;
# JavaMail POP3 provider Sun Microsystems, Inc
protocol=pop3; type=store; class=com.sun.mail.pop3.POP3Store; vendor=Sun Microsystems, Inc;
protocol=pop3s; type=store; class=com.sun.mail.pop3.POP3SSLStore; vendor=Sun Microsystems, Inc;

# JavaMail NNTP provider dog@gnu.org
protocol=nntp; type=store; class=gnu.mail.providers.nntp.NNTPStore; vendor=dog@gnu.org;
protocol=nntp-post; type=transport; class=gnu.mail.providers.nntp.NNTPTransport; vendor=dog@gnu.org;
--

Install this file in your JRE (for me \j2sdk1.4.2_12\jre\lib\javamail.providers)
and install in classpath of your application two Jars gnumail-providers.jar & inetlib.jar

Now you can start your application that use JavaMail of Sun,
that will use gnu.mail.providers.nntp.NNTPStore for get message
and gnu.mail.providers.nntp.NNTPTransport for post nntp message

See chapter 'The Provider Registry' in JavaMail-1.4.pdf


Example :

        NNTP nntp = new NNTP("news.xxxxx.fr", null, null, 119);
        nntp.setDebug(false);
        //nntp.setSocketTimeout(5000);
        try
        {
            /*
            // WARNING : There are >45,000 newsgroups on !
            Folder[] root = nntp.getNNTPRoot(true);
            String home = System.getProperty("user.home");

            File a_F = new File(home, "newsng.txt");
            if (a_F.exists() && !a_F.delete()) throw new Exception("Can't overwrite '"+a_F.getName()+"'");

            RandomAccessFile f_In = null;
            f_In = new RandomAccessFile(a_F,"rw");

            if (root !=null)
            {
                System.err.println("Root Folder : " + root.length);
                for (int i=0, n=root.length; i<n; i++)
                    f_In.writeBytes(root[i].getFullName()+"\n");
            }
            f_In.close();
            */


            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "8859_1"));
            Message[] message = nntp.getNNTPMessage("fr.emplois.offres", true); //fr.test, control.cancel

            // Subscribed to folder, create file '${user.home}/.newsrc at end of session
            // under window make a 'touch .newsrc' with Cygwin or GNU Utilities for Win32
            //nntp.getFolder().setSubscribed(true);

            System.err.println("Newsgroup  : " + nntp.getFolder());
            System.err.println("Separator  : " + nntp.getFolder().getSeparator());
            System.err.println("Message length : " + message.length);

            // inverse...
            for (int i = message.length-1, n = 0; n < i; i--)
            {
                // warning From... we are in world of usenet!
                System.err.println(i + " from : " + NNTP.getFrom(message[i]) + "\tsubject : " + message[i].getSubject());
                System.out.println("Do you want to read message?" + " [YES to read/QUIT to end]");
                String line = reader.readLine();

                // Mark as seen if appropriate
                if ("YES".equals(line))
                {
                    // write output message
                    message[i].writeTo(System.err);

                    // flagged seen
                    //message[i].setFlag(javax.mail.Flags.Flag.SEEN, true);
                }
                else if ("QUIT".equals(line))
                {
                    break;
                }
            }

            //nntp.post("Neo@whatisthematrix.real", "jp.test", "test -ignore", "Welcome to the reality!");
            //nntp.cancel("Neo@whatisthematrix.real", "jp.test", "<8379614.011xxxx406.JavaNNTP.Franck@Nexus>");
        }
        catch (Exception e)
        {
            System.out.println(e);
            System.out.println("Pile : ");
            e.printStackTrace();
        }
        finally
        {
            // ferme la session nntp
            try { nntp.close(true); } catch (MessagingException me)    {}
        }

Source : NNTP.java