Blog - JServlet.com

To content | To menu | To search

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


page 2 of 2 -