Monday 10 June 2013

Sending Email with java

Hi,
I had to send an email using java, I wrote a java class that helps you shooting emails.
I am sharing the source code so that it can be used by others too..
It doesn't support email attachments as it was not the requirement in my case but it can be done too..
Thanks



Things to download
1) java mail API

I used: mailapi.jar



2) My written java Class

package com.breeze.utils;

import java.security.GeneralSecurityException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.breeze.property.AppProperties;
import com.sun.mail.util.MailSSLSocketFactory;

public abstract class EmailAgent {

    public static boolean sendTextOnlyEmail(String to, String from, String subject,String message){
       
       
        final Properties properties=AppProperties.getSystemProperties();
       
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", properties.getProperty("mail.smtp.host")); // for gmail use smtp.gmail.com
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", properties.getProperty("mail.smtp.port"));
        props.put("mail.smtp.socketFactory.port", properties.getProperty("mail.smtp.socketFactory.port"));
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "true");

        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.socketFactory", sf);
       
        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(properties.getProperty("mail.smtp.username"), properties.getProperty("mail.smtp.password"));
            }
        });

        mailSession.setDebug(true); // Enable the debug mode

        Message msg = new MimeMessage( mailSession );

        //--[ Set the FROM, TO, DATE and SUBJECT fields
        try {
            msg.setFrom( new InternetAddress( from ) );
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            msg.setRecipients( Message.RecipientType.TO,InternetAddress.parse(to) );
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //msg.setSentDate(new Date());
        try {
            msg.setSubject( subject );
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //--[ Create the body of the mail
        try {
            msg.setText(message );
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //--[ Ask the Transport class to send our mail message
        try {
            Transport.send( msg );
            return true;
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }   
    }

        public static void main(String[] args){
            EmailAgent.sendTextOnlyEmail("sandeelo.danyal@gmail.com","youremail@domain.com","Need to talk" ,"Hi, This is a testing message. ");
        }
   
}


Use this utility to send text emails.
You can use database to store templates, depends on your needs and requirements. This is a simple code that lets you know how to use mail API.

I have taken a number of values from PROPERTY file to keep the things dynamic.

#----email properties
mail.smtp.host=smtp.company.biz
mail.smtp.port=25
mail.smtp.socketFactory.port=25
mail.smtp.username=username@ursmtp.com
mail.smtp.password=yourPassword
to=to@email.com
from=from@email.com
subject=your subject
emailSuccessMessage=Email has been sent // I have kept this message dynamic, using it on jsp when the //email is sent successully




Using jcaptach in Java

Hi
I went through a number of code snippets as I had to integrate captcha in my web application.
I found the jCaptcha very easy and interesting..

I will like to share my code so that it can be by others too :)..

Good luck!

1) Download the jcpatcha jar fiel
I used : jcaptcha-all-1.0-RC3.jar


Your front end - the jsp file.

 <form name="SimpleServletForm" action="/mbis/simple" method="post">
        <input type="hidden" name="hidCaptchaID" value="<%= session.getId() %>"/>
         <table>
                 <tr>
                     <td>Username </td>
                     <Td> <input type="text" name="username" />  </Td>
                 </tr>
                 <tr>
                     <td>Password </td>
                     <Td> <input type="password" name="password" />  </Td>
                 </tr>
                 <tr>
                    <td > </td>
                    <Td><img src="/mbis/simple" align="middle" alt="Enter the characters appearing in this image" border="1"/></td>
                   
                  </tr>
                
                 <tr>
                    <td > </td>
                    <td><input type="text" name="inCaptchaChars"/></td>
                  </tr>
                 
                 <tr>
                     <td> </td>
                     <Td>  <input type="submit" value="Login" /></Td>
                 </tr>
                
         </table>
         </form>

//====  i have created a file with name SimpleCaptchaServlet
// I have mapped this servlet in web.xml file as


in web.xml file
<servlet>
    <servlet-name>SimpleCaptchaServlet</servlet-name>
    <servlet-class>com.breeze.servlet.SimpleCaptchaServlet</servlet-class>
    <init-param>
      <param-name>ImageType</param-name>
      <param-value>JPG</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SimpleCaptchaServlet</servlet-name>
    <url-pattern>/simple</url-pattern>
  </servlet-mapping>
  <servlet>




/// The actual java file.....
package com.breeze.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SimpleCaptchaServlet
 */

import com.breeze.service.MyCaptchaService;
import com.octo.captcha.service.CaptchaServiceException;
import javax.servlet.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Map;
import javax.imageio.ImageIO;

public class SimpleCaptchaServlet extends HttpServlet{

String sImgType = null;
public void init( ServletConfig servletConfig ) throws ServletException
{
super.init( servletConfig );

// For this servlet, supported image types are PNG and JPG.
sImgType = servletConfig.getInitParameter( "ImageType" );
sImgType = sImgType==null ? "png" : sImgType.trim().toLowerCase();
if ( !sImgType.equalsIgnoreCase("png") && !sImgType.equalsIgnoreCase("jpg") &&
!sImgType.equalsIgnoreCase("jpeg") )
{
  sImgType = "png";
}
}

protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
byte[] captchaBytes;

if ( request.getQueryString()!=null )
{
  response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "GET request should have no query string." );
  return;
}
try
{
  // Session ID is used to identify the particular captcha.
  String captchaId = request.getSession().getId();

  // Generate the captcha image.
  BufferedImage challengeImage = MyCaptchaService.getInstance().getImageChallengeForID(
  captchaId, request.getLocale() );
  ImageIO.write( challengeImage, sImgType, imgOutputStream );
  captchaBytes = imgOutputStream.toByteArray();

  // Clear any existing flag.
  request.getSession().removeAttribute( "PassedCaptcha" );
}
catch( CaptchaServiceException cse )
{
   System.out.println( "CaptchaServiceException - " + cse.getMessage() );
   response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem generating captcha image." );
   return;
}
catch( IOException ioe )
{
   System.out.println( "IOException - " + ioe.getMessage() );
   response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem generating captcha image." );
   return;
}

// Set appropriate http headers.
response.setHeader( "Cache-Control", "no-store" );
response.setHeader( "Pragma", "no-cache" );
response.setDateHeader( "Expires", 0 );
response.setContentType( "image/" + (sImgType.equalsIgnoreCase("png") ? "png" : "jpeg") );

// Write the image to the client.
ServletOutputStream outStream = response.getOutputStream();
outStream.write( captchaBytes );
outStream.flush();
outStream.close();
}

protected void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
// Get the request params.
Map paramMap = request.getParameterMap();
if ( paramMap.isEmpty() )
{
  response.sendError( HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Post method not allowed without parameters." );
  return;
}
String[] arr1 = (String[])paramMap.get( "hidCaptchaID" );
String[] arr2 = (String[])paramMap.get( "inCaptchaChars" );
if ( arr1==null || arr2==null  )
{
  response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Expected parameters were not found." );
  return;
}

String sessId = request.getSession().getId();
String incomingCaptchaId = arr1.length>0 ? arr1[0] : "";
String inputChars = arr2.length>0 ? arr2[0] : "";

// Check validity and consistency of the data.
if ( sessId==null || incomingCaptchaId==null || !sessId.equals(incomingCaptchaId) )
{
  response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Browser must support session cookies." );
  return;
}

// Validate whether input from user is correct.
System.out.println( "Validating - inputChars are: " + inputChars );
boolean passedCaptchaTest = validateCaptcha( incomingCaptchaId, inputChars );

// Set flag into session.
request.getSession().setAttribute( "PassedCaptcha", new Boolean(passedCaptchaTest) );

// Forward request to results page.
request.setAttribute("username", request.getParameter("username"));
request.setAttribute("password", request.getParameter("password"));

if(passedCaptchaTest){   // If correct CAPTCHA code inserted, Send it to the Login servlet
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login");
    rd.forward( request, response );
}
else {
    request.setAttribute("loginMessage", "Invalid Captcha code....");
    getServletContext().getRequestDispatcher("/pages/index.jsp").forward(request, response);
 }
}

private boolean validateCaptcha( String captchaId, String inputChars )
{
boolean bValidated = false;
try
{
  bValidated = MyCaptchaService.getInstance().validateResponseForID( captchaId, inputChars );
}
catch( CaptchaServiceException cse )
{}
return bValidated;
}
}



If you are interested to get the source code..just message me, I will send the source code too..
I am not attaching it here because I need to get it separated from my web application.

Thanks.