Monday, October 14, 2013

How to send an email using Java API & Gmail account


Below blog explains about sending an email using Gmail email address as from email and Java API

Below is the sample code snippet to send email using Java Mail API.

Download the Java Mail Jar and set in class path
Here is the link to download java-mail.jar  http://www.oracle.com/technetwork/java/index-138643.html

       
import com.sun.mail.util.MailSSLSocketFactory;

import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage;

import java.net.URL;

import java.security.GeneralSecurityException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import javax.mail.Session;
    /**
   * De limit the toEmail List
   * Authenticate
   * @param msg
   * @param subject
   * @param toEmail
   * @param fromEmail
   * @return
   * @throws Exception
   */
  public static String sendEmail(String msg, String subject, String toEmail, String fromEmail)
    throws Exception
  {
    String toEmails[] = toEmail.split(",");
    System.out.println("TO:::FROM:::SUBJ:::BODY:::" + toEmail + "-" + fromEmail + "-" + subject + "-" + msg);

    Session session = setSessionAuthentication();
    InternetAddress from = new InternetAddress(fromEmail);
    InternetAddress to[] = new InternetAddress[toEmails.length];
    for (int c = 0; c < toEmails.length; c++)
    {
      to[c] = new InternetAddress(toEmails[c]);
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.addRecipients(Message.RecipientType.TO, to);
    message.setSubject(subject);
    message.setText(msg);
    Transport.send(message);
    // msg="OK Msg Posted Successfully";
    return "EMail Sent Successfully";
  }

  /**
   *
   * @return
   * @throws Exception
   */
  public static Session setSessionAuthentication()
    throws Exception
  {
    final String username = "FM@gmail.com";
    final String password = "GMAIL PASSWORD";
    //Using SSL
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    // USING TLS
    //        Properties props = new Properties();
    //        props.put("mail.smtp.auth", "true");
    //        props.put("mail.smtp.starttls.enable", "true");
    //        props.put("mail.smtp.host", "smtp.gmail.com");
    //        props.put("mail.smtp.port", "587");
    props.put("mail.debug", "true");
    MailSSLSocketFactory sf = null;
    try
    {
      sf = new MailSSLSocketFactory();
    }
    catch (GeneralSecurityException e1)
    {
      e1.printStackTrace();
    }
    sf.setTrustAllHosts(true);
    props.put("mail.smtp.ssl.socketFactory", sf);
    Session session = Session.getInstance(props, new javax.mail.Authenticator()
      {
        protected PasswordAuthentication getPasswordAuthentication()
        {
          return new PasswordAuthentication(username, password);
        }
      });
    return session;
  }
       
 

Monday, October 7, 2013

How to find Fiscal Month Start & End Date , Fiscal Week Start & End Date for a given Date using Java

This blog explains about getting Fiscal Month Start & End date , Fiscal Week start & end date based on given date using Java API

From the below diagram,

 For October 2013, 9/29/2013 is Fiscal Month Start Date , 11/9/2013 is Fiscal Month End Date
Similarly - 9/29/2013 is fiscal week start date , 10/5/2013 is fiscal week end date for any date b/w 1st to 5th in October.


Implementation
       
    private static GregorianCalendar gregorianCalendar;
    private static final int MAX_WEEKS = 6;

      private static void init(Date date) {
        gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.clear();
        gregorianCalendar.setTime(date);
    }

    /**
     * Returns the Start date of fiscal week based on given input Date
     * @param date
     * @return
     * @throws Exception
     */

    public static Date getFiscalWeekStartDate(Date date) throws Exception {
        if (date != null) {
            init(date);
            return getFiscalWeekStartDate(gregorianCalendar);
        }
        return null;

    }

    private static Date getFiscalWeekStartDate(GregorianCalendar gregorianCalendar) {
        int correction = 1 - gregorianCalendar.get(GregorianCalendar.DAY_OF_WEEK);
        gregorianCalendar.add(Calendar.DATE, correction);
        return gregorianCalendar.getTime();
    }

    /**
     * Returns the Start date of fiscal week based on given input Date
     * @param date
     * @return
     * @throws Exception
     */

    public static Date getFiscalWeekEndDate(Date date) throws Exception {
        if (date != null) {
            init(date);
            return getFiscalWeekEndDate(gregorianCalendar);
        }
        return null;
    }

    private static Date getFiscalWeekEndDate(GregorianCalendar gregorianCalendar) {
        int correction = 7 - gregorianCalendar.get(GregorianCalendar.DAY_OF_WEEK);
        gregorianCalendar.add(Calendar.DATE, correction);
        return gregorianCalendar.getTime();
    }

    /**
     * Returns the Start date of fiscal month based on given input Date
     * @param date
     * @return
     * @throws Exception
     */

    public static Date getFiscalMonthStartDate(Date date) throws Exception {
        if (date != null) {
            init(date);
            int correction = 1 - gregorianCalendar.get(GregorianCalendar.DAY_OF_MONTH);
            gregorianCalendar.add(Calendar.DATE, correction);
            return getFiscalWeekStartDate(gregorianCalendar);
        }
        return null;

    }

    /**
     * Returns the End date of fiscal month based on given input Date
     * @param date
     * @return
     * @throws Exception
     */

    public static Date getFiscalMonthEndDate(Date date) throws Exception {
        if (date != null) {
            int correction = 0;
            init(date);
            int num_of_weeks = gregorianCalendar.getActualMaximum(Calendar.WEEK_OF_MONTH);
            int cur_week = gregorianCalendar.get(Calendar.WEEK_OF_MONTH);
            if (num_of_weeks < MAX_WEEKS) {
                correction = num_of_weeks - cur_week + 1;
            } else {
                correction = num_of_weeks - cur_week;
            }
            gregorianCalendar.add(Calendar.WEEK_OF_MONTH, correction);
            return getFiscalWeekEndDate(gregorianCalendar);
        }

        return null;
    }