Search This Blog

Wednesday, April 30, 2014

LDAP - ADS User Creation

Here is the example to create LDAP - ADS User Creation.

Files:-
Create a main folder and paste this two properties file.
Create a sub folders like com/vijay/ldap and paste the java content in Ldap.java.

Ldap.properties
         To make connection with your Ldap/ADS.
Ldap-user-settings.properties
         To make settings for your new user.
 Ldap.java
          It is a java program which can connect ldap and create user based on your distinguish Name.


ldap.properties

#* @author drvijay
#* @date 29-04-2014 4PM

ldap.initial.context.factory=com.sun.jndi.ldap.LdapCtxFactory
ldap.security.authentication=simple

ldap.domain.name=domain.com
ldap.domain.root=DC=sdex,DC=com
ldap.admin.name=CN=Administrator,CN=Users,DC=domain,DC=com
ldap.organisationUnit=ou=subOrg,ou=parentOrg
ldap.admin.pass=test123
ldap.domain.url=ldap://127.0.0.1:389



#ldap.organisationUnit=ou=subOrg,ou=parentOrg  you can change the ou= based on your ldap structure


ldap-user-settings.properties

#* @author drvijay
#* @date 29-04-2014 4PM

#loop configuration
ldap.concatenate.start.value=1
ldap.concatenate.end.value=1

#loop attributes
ldap.userName=userName{0}
ldap.firstName=Vijay{0}
ldap.displayName={0} D R

#repeated attributes
ldap.lastName=P
ldap.userPassword=test123
ldap.mobile=9842088860
ldap.company=infovijay
ldap.mail=drvijayy2k2@gmail.com
ldap.postalCode=636702
ldap.st=TN
ldap.city=DPI
ldap.country=IN


Ldap.Java

package com.vijay.ldap;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

/**
 *
 * @author drvijay
 * @date 29-04-2014 4PM
 */

public class Ldap
{

    private static ResourceBundle                ldapSystemProperties        = ResourceBundle.getBundle ( "ldap" );
    private static ResourceBundle                ldapUserSettingsProperties    = ResourceBundle.getBundle ( "ldap-user-settings" );

    private static String                        DOMAIN_NAME                    = ldapSystemProperties.getString ( "ldap.domain.name" );
    private static String                        DOMAIN_ROOT                    = ldapSystemProperties.getString ( "ldap.domain.root" );
    private static String                        ADMIN_NAME                    = ldapSystemProperties.getString ( "ldap.admin.name" );
    private static String                        ADMIN_PASS                    = ldapSystemProperties.getString ( "ldap.admin.pass" );
    private static String                        DOMAIN_URL                    = ldapSystemProperties.getString ( "ldap.domain.url" );
    private static String                        INITIAL_CONTEXT_FACTORY        = ldapSystemProperties.getString ( "ldap.initial.context.factory" );
    private static String                        SECURITY_AUTHENTICATION        = ldapSystemProperties.getString ( "ldap.security.authentication" );
    private static String                        _organisationUnit            = ldapSystemProperties.getString ( "ldap.organisationUnit" );

    // some useful constants from lmaccess.h
    private static int                            UF_ACCOUNTDISABLE            = 0x0002;
    private static int                            UF_PASSWD_NOTREQD            = 0x0020;
    private static int                            UF_PASSWD_CANT_CHANGE        = 0x0040;
    private static int                            UF_NORMAL_ACCOUNT            = 0x0200;
    private static int                            UF_DONT_EXPIRE_PASSWD        = 0x10000;
    private static int                            UF_PASSWORD_EXPIRED            = 0x800000;

    private static String                        _userName                    = ldapUserSettingsProperties.getString ( "ldap.userName" );
    private static String                        _firstName                    = ldapUserSettingsProperties.getString ( "ldap.firstName" );
    private static String                        _lastName                    = ldapUserSettingsProperties.getString ( "ldap.lastName" );
    private static String                        _userPassword                = ldapUserSettingsProperties.getString ( "ldap.userPassword" );
    private static String                        _mobile                        = ldapUserSettingsProperties.getString ( "ldap.mobile" );
    private static String                        _company                    = ldapUserSettingsProperties.getString ( "ldap.company" );
    private static String                        _displayName                = ldapUserSettingsProperties.getString ( "ldap.displayName" );
    private static String                        _mail                        = ldapUserSettingsProperties.getString ( "ldap.mail" );
    private static String                        _postalCode                    = ldapUserSettingsProperties.getString ( "ldap.postalCode" );
    private static String                        _st                            = ldapUserSettingsProperties.getString ( "ldap.st" );
    private static String                        _city                        = ldapUserSettingsProperties.getString ( "ldap.city" );
    private static String                        _country                    = ldapUserSettingsProperties.getString ( "ldap.country" );

    private static String                        cnValue;

    private static int                            loopStart                    = Integer.parseInt ( ldapUserSettingsProperties.getString ( "ldap.concatenate.start.value" ) );
    private static int                            loopEnd                        = Integer.parseInt ( ldapUserSettingsProperties.getString ( "ldap.concatenate.end.value" ) );

    private static LdapContext                    context;
    private static Hashtable     env                            = new Hashtable ();

    /**
     * Instantiates a new ldap.
     */
    public Ldap ()
    {
    }

    /**
     * Instantiates a new ldap.
     *
     * @param userName
     *            the user name
     * @param firstName
     *            the first name
     * @param lastName
     *            the last name
     * @param organisationUnit
     *            the organisation unit
     */
    public Ldap ( String userName, String firstName, String lastName, String organisationUnit )
    {
        this._userName = userName;
        this._firstName = firstName;
        this._lastName = lastName;
        this._organisationUnit = organisationUnit;
    }

    /**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main ( String [] args )
    {
        // Ldap user = new Ldap ( userName, firstName, lastName, organisationUnit );
        Ldap user = new Ldap ();

        try
        {
            env.put ( Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY );
            env.put ( Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION );
            env.put ( Context.SECURITY_PRINCIPAL, ADMIN_NAME );
            env.put ( Context.SECURITY_CREDENTIALS, ADMIN_PASS );
            env.put ( Context.PROVIDER_URL, DOMAIN_URL );
            context = new InitialLdapContext ( env, null );

            for ( int i = loopStart; i <= loopEnd; i++ )
            {
                try
                {
                    // replace dynamic parameters from properties
                    _userName = MessageFormat.format ( ldapUserSettingsProperties.getString ( "ldap.userName" ), i );
                    _firstName = MessageFormat.format ( ldapUserSettingsProperties.getString ( "ldap.firstName" ), i );
                    _displayName = MessageFormat.format ( ldapUserSettingsProperties.getString ( "ldap.displayName" ), _firstName );

                    // create user
                    System.out.println ( "User : " + _userName + " created Status : " + user.addUser () );

                    // DirContext sslCtx = new InitialDirContext ( env );
                    // changePassword ( sslCtx, getUserDN ( cnValue, user.organisationUnit ), "test123" );
                }
                catch ( Exception e )
                {
                    System.err.println ( e.getMessage () );
                    e.printStackTrace ();
                }
            }

        }
        catch ( NamingException e )
        {
            System.err.println ( "Problem creating object: " + e );
            e.printStackTrace ();
        }
        catch ( Exception e )
        {
            System.err.println ( "Problem creating object: " + e );
            e.printStackTrace ();
        }
    }

    /**
     * Gets the user dn.
     *
     * @param aUsername
     *            the a username
     * @param aOU
     *            the a ou
     * @return the user dn
     */
    private static String getUserDN ( String aUsername, String aOU )
    {
        return "cn=" + aUsername + "," + aOU + "," + DOMAIN_ROOT;
    }

    /**
     * Adds the user.
     *
     * @return true, if successful
     * @throws NamingException
     *             the naming exception
     */
    public boolean addUser () throws NamingException
    {

        Attributes container = new BasicAttributes ();

        try
        {

            Attribute objClasses = new BasicAttribute ( "objectClass" );
            objClasses.add ( "top" );
            objClasses.add ( "person" );
            objClasses.add ( "organizationalPerson" );
            objClasses.add ( "user" );
            container.put ( objClasses );

            cnValue = new StringBuffer ( _firstName ).append ( " " ).append ( _lastName ).toString ();

            Attribute cn = new BasicAttribute ( "cn", cnValue );
            Attribute sAMAccountName = new BasicAttribute ( "sAMAccountName", _userName );
            Attribute principalName = new BasicAttribute ( "userPrincipalName", _userName + "@" + DOMAIN_NAME );

            Attribute givenName = new BasicAttribute ( "givenName", _firstName );
            Attribute sn = new BasicAttribute ( "sn", _lastName );
            Attribute uid = new BasicAttribute ( "uid", _userName );

            Attribute userPassword = new BasicAttribute ( "userpassword", _userPassword );
            Attribute mobile = new BasicAttribute ( "mobile", _mobile );
            Attribute company = new BasicAttribute ( "company", _company );
            Attribute displayName = new BasicAttribute ( "displayName", _displayName );
            Attribute mail = new BasicAttribute ( "mail", _mail );
            Attribute postalCode = new BasicAttribute ( "postalCode", _postalCode );
            Attribute st = new BasicAttribute ( "st", _st );
            Attribute l = new BasicAttribute ( "l", _city );
            Attribute c = new BasicAttribute ( "c", _country );
            Attribute userAccountControl = new BasicAttribute ( "userAccountControl", Integer.toString ( UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_PASSWORD_EXPIRED + UF_DONT_EXPIRE_PASSWD ) );

            container.put ( sAMAccountName );
            container.put ( principalName );
            container.put ( cn );
            container.put ( sn );
            container.put ( givenName );
            container.put ( uid );
            container.put ( c );
            container.put ( l );
            container.put ( st );
            container.put ( postalCode );
            container.put ( mail );
            container.put ( displayName );
            container.put ( company );
            container.put ( mobile );
            container.put ( userAccountControl );
            container.put ( userPassword );

            context.createSubcontext ( getUserDN ( cnValue, _organisationUnit ), container );
            return true;
        }
        catch ( Exception e )
        {
            e.printStackTrace ();
            return false;
        }
    }

    /**
     * Gets the time.
     *
     * @param pwdLastSet
     *            the pwd last set
     * @return the time
     */
    private static Calendar getTime ( long pwdLastSet )
    {
        long javaTime = pwdLastSet - 0x19db1ded53e8000L;
        javaTime /= 10000;

        Calendar cal = Calendar.getInstance ();
        cal.setTimeInMillis ( javaTime );
        return cal;
    }

    /**
     * Encode password.
     *
     * @param pass
     *            the pass
     * @return the byte[]
     * @throws UnsupportedEncodingException
     *             the unsupported encoding exception
     */
    private static byte [] encodePassword ( String pass ) throws UnsupportedEncodingException
    {
        String ATT_ENCODING = "UTF-16LE";
        String pwd = "\"" + pass + "\"";
        byte bytes[] = pwd.getBytes ( ATT_ENCODING );

        return bytes;
    }

    /**
     * Change password.
     *
     * @param ctx
     *            the ctx
     * @param argRDN
     *            the arg rdn
     * @param argNewPassword
     *            the arg new password
     * @throws NamingException
     *             the naming exception
     */
    public static void changePassword ( DirContext ctx, String argRDN, String argNewPassword ) throws NamingException
    {

        ModificationItem [] modificationItem = new ModificationItem[1];
        try
        {
            modificationItem[0] = new ModificationItem ( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute ( "unicodePwd", encodePassword ( argNewPassword ) ) );
            ctx.modifyAttributes ( argRDN, modificationItem );
        }
        catch ( UnsupportedEncodingException e1 )
        {
            throw new RuntimeException ( e1.toString () );
        }
        catch ( NamingException e1 )
        {
            throw e1;
        }
    }

}








Tuesday, April 22, 2014

Point to Point Queue Messaging

Point to Point Messaging Program

The Hello World application consists of a sender application that sends a "Hello" message to a queue. This message will be received by one queue receiver connected to the queue in question. If no receivers are connected, the message will be retained on the queue. If more queue receivers are connected, they will receive messages in a round-robin fashion
There are four sample programs for this section:
  • Queue Sender
  • Synchronous Queue Receiver
  • Asynchronous Queue Receiver
  • Queue Browser
Note that none of the examples in this section show code for handling exceptions. Although this improves the readability of the example code, application programmers should notice that almost all methods in the JMS API's may raise a JMSException if the JMS provider fails.

Queue Sender

The queue sender application performs the following steps:
  1. Obtain an InitialContext object for the JMS server.
  2. Use the context object to lookup a specific queue, in this case, queue0.
  3. Use the context object to lookup the queue connection factory. You only need to specify the queue/connectionFactory with the lookup because the batch file that you run this sample from has set the System properties to point to the appropriate root context for the System namespace. If you were using the JMS server with the Novell exteNd Application Server, you would have to specify the lookup as follows:
     QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
                lookup("iiop://localhost:53506/queue/connectionFactory");
     
  4. Use the QueueConnectionFactory to create a QueueConnection. The QueueConnection represents a physical connection to the JMS server.
  5. Create a queue session. The first parameter in the createQueueSession method decides whether or not the session is transacted. Here, we use a non-transacted session. The second parameter decided the delivery mode, which is never used for sending applications.
  6. Create a queue sender for queue0 and create a message.
  7. Send the "Hello" message to queue0.
  8. Close the queue connection. This will in turn close both the session and the QueueSender.
The full source code for the sender application is shown below:
package pointToPoint;
                                                                           
import javax.naming.InitialContext;
                                                                           
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.QueueSender;
import javax.jms.DeliveryMode;
import javax.jms.QueueSession;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
                                                                           
public class Sender
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
       InitialContext ctx = new InitialContext();
                                                                          
       // lookup the queue object
       Queue queue = (Queue) ctx.lookup("queue/queue0");
                                                                          
       // lookup the queue connection factory
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
           lookup("queue/connectionFactory");
                                                                          
       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();
                                                                          
       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.DUPS_OK_ACKNOWLEDGE);
                                                                          
       // create a queue sender
       QueueSender queueSender = queueSession.createSender(queue);
       queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                                                                          
       // create a simple message to say "Hello"
       TextMessage message = queueSession.createTextMessage("Hello");
                                                                          
       // send the message
       queueSender.send(message);
                                                                          
       // print what we did
       System.out.println("sent: " + message.getText());
                                                                          
       // close the queue connection
       queueConn.close();
    }
}
The Sender class sets the delivery mode to NON_PERSISTENT before sending the message. This means that the message will be lost in case the JMS server crashes. Since NON_PERSISTENT messages giver better performance than PERSISTENT messages, applications should set the delivery mode to NON_PERSISTENT whenever guaranteed delivery is not a requirement.

Synchronous Queue Receiver

The receive application performs the same initial steps as the queue sender because you always have to find a queue object using the initial context, connect to the queue and create a session as shown here.
Instead of a QueueSender object, the receiver application creates a QueueReceiver from which messages can be received synchronously. Note that the receiver application must start the connection before any messages can be received.
The receiver application uses a non-transacted session with automatic message acknowledgement. This means that message will automatically be acknowledged by the session right before the receive method returns the message to the application.
Below is the source for the Receiver class:

package pointToPoint;
                                                                           
import javax.naming.InitialContext;
                                                                           
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.QueueSession;
import javax.jms.QueueReceiver;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
                                                                           
public class Receiver
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
       InitialContext ctx = new InitialContext();
                                                                          
       // lookup the queue object
       Queue queue = (Queue) ctx.lookup("queue/queue0");
                                                                          
       // lookup the queue connection factory
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
           lookup("queue/connectionFactory");
                                                                          
       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();
                                                                          
       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.AUTO_ACKNOWLEDGE);
                                                                          
       // create a queue receiver
       QueueReceiver queueReceiver = queueSession.createReceiver(queue);
                                                                          
       // start the connection
       queueConn.start();
                                                                          
       // receive a message
       TextMessage message = (TextMessage) queueReceiver.receive();
                                                                          
       // print the message
       System.out.println("received: " + message.getText());
                                                                          
       // close the queue connection
       queueConn.close();
    }
}
If the connection is not started, the receive method will block forever (or until some other thread starts the connection). If a client want to temporarily stop delivery of messages, the connection can be stopped and then re-started later.

Asynchronous Queue Receiver

The AsyncReceiver class illustrates the use of message listeners. A message listener is a regular Java class that implements the MessageListener interface. This interface has a single onMessage method, which is called by JMS when messages arrive at a destination.
As with the synchronous receiver, the AsyncReceiver class performs the same initial steps to create a QueueReceiver. Then, the setMessageListener method is called to register this as a message listener. As with a synchronous receiver, messages will not be delivered until the start method is called on the connection.
Since acknowledge mode is set to automatic, JMS will acknowledge messages right after calls to the onMessage method returns. Note that onMessage is not allowed to throw any exceptions. You must catch all exceptions and deal with them somehow in the onMessage method.
In the synchronous receiver, the receive method can raise an exception if the JMS provider fails. Due to its asynchronous nature, this is not possible with message listeners. Therefore, it is possible to register an exception listener with the connection, which can pick up such exceptions.
Below is the full source for the AsyncReceiver class:
package pointToPoint;
                                                                           
import javax.naming.InitialContext;
                                                                           
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Message;
import javax.jms.TextMessage;
import javax.jms.MessageListener;
import javax.jms.JMSException;
import javax.jms.ExceptionListener;
import javax.jms.QueueSession;
import javax.jms.QueueReceiver;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
                                                                           
public class AsyncReceiver implements MessageListener, ExceptionListener
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
       InitialContext ctx = new InitialContext();
                                                                          
       // lookup the queue object
       Queue queue = (Queue) ctx.lookup("queue/queue0");
                                                                          
       // lookup the queue connection factory
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
           lookup("queue/connectionFactory");
                                                                          
       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();
                                                                          
       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.AUTO_ACKNOWLEDGE);
                                                                          
       // create a queue receiver
       QueueReceiver queueReceiver = queueSession.createReceiver(queue);
                                                                          
       // set an asynchronous message listener
       AsyncReceiver asyncReceiver = new AsyncReceiver();
       queueReceiver.setMessageListener(asyncReceiver);
                                                                          
       // set an asynchronous exception listener on the connection
       queueConn.setExceptionListener(asyncReceiver);
                                                                          
       // start the connection
       queueConn.start();
                                                                          
       // wait for messages
       System.out.print("waiting for messages");
       for (int i = 0; i < 10; i++) {
          Thread.sleep(1000);
          System.out.print(".");
       }
       System.out.println();
                                                                          
       // close the queue connection
       queueConn.close();
    }
                                                                           
    /**
       This method is called asynchronously by JMS when a message arrives
       at the queue. Client applications must not throw any exceptions in
       the onMessage method.
       @param message A JMS message.
     */
    public void onMessage(Message message)
    {
       TextMessage msg = (TextMessage) message;
       try {
          System.out.println("received: " + msg.getText());
       } catch (JMSException ex) {
          ex.printStackTrace();
       }
    }
                                                                           
    /**
       This method is called asynchronously by JMS when some error occurs.
       When using an asynchronous message listener it is recommended to use
       an exception listener also since JMS have no way to report errors
       otherwise.
       @param exception A JMS exception.
     */
    public void onException(JMSException exception)
    {
       System.err.println("an error occurred: " + exception);
    }
}
As documented in the source code, it is recommended to always set a connection exception listener when using asynchronous message listeners. This will allow you to detect any runtime problems, including a crash of the JMS server.
The JMSException API supports the getLinkedException method, which can be used to get the root cause of the exception (if any). As an example, if you raise a RuntimeException in the onMessage method, the linked exception will be this runtime exception when onException is called.

Queue Browser

A queue browser can be used to look at a queue without consuming any messages. The queue browser must perform the same initial steps as any other JMS client application, i.e. get a session object, which is a factory for QueueBrowser objects.
The QueueBrowser supports an iterator, which can be used to enumerate the messages on a queue. The following example shows how to count the number of messages on a queue. Note that acknowledge mode is not meaningful to a queue browser:
package pointToPoint;
                                                                           
import java.util.Enumeration;
                                                                           
import javax.naming.InitialContext;
                                                                           
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Message;
import javax.jms.QueueSession;
import javax.jms.QueueBrowser;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
                                                                           
public class Browser
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
       InitialContext ctx = new InitialContext();
                                                                          
       // lookup the queue object
       Queue queue = (Queue) ctx.lookup("queue/queue0");
                                                                          
       // lookup the queue connection factory
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
           lookup("queue/connectionFactory");
                                                                          
       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();
                                                                          
       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.AUTO_ACKNOWLEDGE);
                                                                          
       // create a queue browser
       QueueBrowser queueBrowser = queueSession.createBrowser(queue);
                                                                          
       // start the connection
       queueConn.start();
                                                                          
       // browse the messages
       Enumeration e = queueBrowser.getEnumeration();
       int numMsgs = 0;
                                                                          
       // count number of messages
       while (e.hasMoreElements()) {
          Message message = (Message) e.nextElement();
          numMsgs++;
       }
                                                                          
       System.out.println(queue + " has " + numMsgs + " messages");
                                                                          
       // close the queue connection
       queueConn.close();
    }
}
The order of messages returned by the enumeration reflects the order of messages a regular message receiver would see. Note that a queue browser represents a static snapshop of the queue. If more messages are added to the queue while browsing, this will not be available to the queue browser.

Thanks to 
http://www.novell.com  [Copy Paste]



Wednesday, April 16, 2014

How to Send Mail to Outlook i Calender Meeting Remainder ( ICS )


//use below sample and enjoy, which i taken from another site and modify with my choice..
//hope this will help you a lot and give me a copy of yours if u done any modification..

package com.test;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailRemainder
{
    public BodyPart buildHtmlTextPart () throws MessagingException
    {

        MimeBodyPart descriptionPart = new MimeBodyPart ();

        // Note: even if the content is spcified as being text/html, outlook won't read correctly tables at all
        // and only some properties from div:s. Thus, try to avoid too fancy content
        String content = "Sample Body Content";
        descriptionPart.setContent ( content, "text/html; charset=utf-8" );

        return descriptionPart;
    }

    // define somewhere the icalendar date format
    private static SimpleDateFormat    iCalendarDateFormat    = new SimpleDateFormat ( "yyyyMMdd'T'HHmm'00'" );

    public BodyPart buildCalendarPart (String fromMailId, String location, String description ) throws Exception
    {

        BodyPart calendarPart = new MimeBodyPart ();

        //System.out.println ( TimeZone.getTimeZone ( "UTC" ) );
        Calendar cal = Calendar.getInstance ();   //TimeZone.getDefault () //TimeZone.getTimeZone ( "UTC" )
        //cal.add ( Calendar.DAY_OF_MONTH, 1 );
        cal.add ( Calendar.MINUTE, 10 );
        Date start = cal.getTime ();
        System.out.println ( "Meeting Start Time : " + start );
       
        //cal.add ( Calendar.HOUR_OF_DAY, 3 );
        cal.add ( Calendar.MINUTE, 15 );
        Date end = cal.getTime ();
        System.out.println ( "Meeting End Time : " + end );
       
        // check the icalendar spec in order to build a more complicated meeting request
        String calendarContent =
                "BEGIN:VCALENDAR\n"
               
                    + "METHOD:REQUEST\n"
                    + "PRODID:-//Sdex Portal//NONSGML Sdex//EN\n"
                    + "VERSION:2.0\n"
               
                    + "BEGIN:VTIMEZONE\n"
                    + "TZID:India Standard Time\n"
                        + "BEGIN:STANDARD\n"
                        + "DTSTART:" + iCalendarDateFormat.format ( start ) + "\n"
                        + "TZOFFSETFROM:+0530\n"
                        + "TZOFFSETTO:+0530\n"
                        + "END:STANDARD\n"
                    + "END:VTIMEZONE\n"
                   
                    + "BEGIN:VEVENT\n"
                    + "DTSTAMP:" + iCalendarDateFormat.format ( start ) + "\n"
                    + "DTSTART:" + iCalendarDateFormat.format ( start ) + "\n"
                    + "DTEND:" + iCalendarDateFormat.format ( end ) + "\n"
                    + "SUMMARY:test request\n"
                    + "UID:" + Math.random () +"\n"
                    + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:"+ fromMailId +"\n"
                    + "ORGANIZER:MAILTO:"+ fromMailId +"\n"
                    + "LOCATION:"+ location +"\n"
                    + "DESCRIPTION:"+ description +"\n"
                    + "SEQUENCE:1\n"
                    + "PRIORITY:1\n"
                    + "CLASS:PUBLIC\n"
                    + "STATUS:CONFIRMED\n"
                    + "TRANSP:OPAQUE\n"
                        + "BEGIN:VALARM\n"
                        + "ACTION:DISPLAY\n"
                        + "DESCRIPTION:REMINDER\n"
                        + "TRIGGER;RELATED=START:-PT00H15M00S\n"
                        + "END:VALARM\n"
                    + "END:VEVENT\n"
                   
                + "END:VCALENDAR";

        calendarPart.addHeader ( "Content-Class", "urn:content-classes:calendarmessage" );
        calendarPart.setContent ( calendarContent, "text/calendar;method=REQUEST" );

        return calendarPart;
    }

    public static void main ( String args[] ) throws Exception
    {
        String fromMailId = "vijay@XXXXXXX.com";
        String toMailId = "vkumar@XXXXXXX.com";
        final String userName = "vijay@XXXXXXX.com";
        final String password = "test123";
        String protocol = "smtp";
        int port  = 25;
       
        Session session = null;
        // Security.addProvider ( new com.sun.net.ssl.internal.ssl.Provider () ); //this will use for SSL/HTTPS
        Properties props = new Properties ();
        props.setProperty ( "mail.transport.protocol", protocol );
        props.setProperty ( "mail.host", "smtp.yourserver.com" );
        props.put ( "mail.debug", "false" );
        props.put ( "mail.smtp.port", port );
        if ( Boolean.parseBoolean ( "true" ) )
        {
            props.put ( "mail.smtp.auth", "true" );
            props.put ( "mail.smtp.socketFactory.port", port );
        }
        if ( Boolean.parseBoolean ( "false" ) )
        {
            props.put ( "mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory" );
            props.put ( "mail.smtp.socketFactory.fallback", "false" );
        }
        if ( Boolean.parseBoolean ( "true" ) )
        {
            session = Session.getDefaultInstance ( props, new javax.mail.Authenticator () {
                // @Override
                protected PasswordAuthentication getPasswordAuthentication ()
                {
                    return new PasswordAuthentication ( userName, password );
                }
            } );
        }
        else
        {
            session = Session.getInstance ( props );
        }

        // session.setDebug ( true );

        EmailRemainder emailRemainder = new EmailRemainder ();
        MimeMessage message = new MimeMessage ( session );
        message.setFrom ( new InternetAddress ( fromMailId ) );
        message.setSubject ( "Subject: Hi 2" );
        message.addRecipient ( Message.RecipientType.TO, new InternetAddress ( toMailId ) );
        // Create an alternative Multipart
        Multipart multipart = new MimeMultipart ( "alternative" );
        // part 1, html text
        BodyPart messageBodyPart = emailRemainder.buildHtmlTextPart ();
        multipart.addBodyPart ( messageBodyPart );

        // Add part two, the calendar
        BodyPart calendarPart = emailRemainder.buildCalendarPart ( fromMailId, "Meeting on your domain.com", "sample description" );
        multipart.addBodyPart ( calendarPart );

        // Put the multipart in message
        message.setContent ( multipart );

        // send the message
        Transport transport = session.getTransport ( protocol );
        transport.connect ();
        transport.sendMessage ( message, message.getAllRecipients () );
        transport.close ();

            System.out.println ("done");
    }
}



Hit Counter


View My Stats