Monday, October 24, 2016

Sorting Algorithm - Bubble Sort

Bubble Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in some random order.

For Example:

First Pass:

( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:

( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )

Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Java implementations of Bubble Sort:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class BubbleSortApp
{
public void printArray(int arr[])
{
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i] + " ");
}
System.out.println(" ");
}

public  void bubbleSort(int arr[])
   {
       int n = arr.length;
       for (int i = 0; i < n-1; i++)
           for (int j = 0; j < n-i-1; j++)
               if (arr[j] > arr[j+1])
               {                  
                   int temp = arr[j];
                   arr[j] = arr[j+1];
                   arr[j+1] = temp;
               }
   }

public static void main(String[] args)
{
BubbleSortApp ob = new BubbleSortApp();
        int arr[] = {64, 34, 25, 12, 22, 11, 90};
        ob.bubbleSort(arr);
        System.out.println("Sorted array");
        ob.printArray(arr);
}

}

Output: 

Sorted array
11
12
22
25
34
64
90

Worst and Average Case Time Complexity: O(n*n).
Worst case occurs when array is reverse sorted.

Best Case Time Complexity: O(n).
Best case occurs when array is already sorted.

Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.

Sorting In Place: Yes

Stable: Yes

Due to its simplicity, bubble sort is often used to introduce the concept of a sorting algorithm.
In computer graphics it is popular for its capability to detect a very small error (like swap of just two elements) in almost-sorted arrays and fix it with just linear complexity (2n).

For example, it is used in a polygon filling algorithm, where bounding lines are sorted by their x coordinate at a specific scan line (a line parallel to x axis) and with incrementing y their order changes (two elements are swapped) only at intersections of two lines


Sorting Algorithm - Selection Sort

Selection Sort

The selection sort algorithm sorts an array by repeatedly finding the minimum element from unsorted part and putting it at the beginning.

The algorithm maintains two subarrays in a given array.

1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.

In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray.

Note: consider it in ascending order.

Time Complexity:  O(n^2)
Space Complexity: O(1) because the good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation.

Sample Code Implementation in Java:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class SelectionSortApp
{

public void printArray(int arr[])
{
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i] + " ");
}
System.out.println(" ");
}

public void selectionSort(int arr[])
{
int min_idx;
int n=arr.length;

for(int i=0;i<n-1;i++)
{
min_idx=i;
for(int j=i+1; j<n;j++)
if(arr[j] <arr[min_idx])
min_idx=j;

int temp=arr[min_idx];
arr[min_idx]=arr[i];
arr[i]=temp;
}
}

public static void main(String[] args)
{
SelectionSortApp ob=new SelectionSortApp();
int arr[] = {64,25,12,22,11};
        ob.selectionSort(arr);
        System.out.println("Sorted array");
        ob.printArray(arr);
}
}

OutPut: Sorted array

11
12
22
25
64


Thursday, October 20, 2016

Happy Number(YepMe Interview Question) in Java

Happy Number

I have been interviewed  in YepMe few days back .It was very nice interview taken by the technical interviewer ,simply a nice guy.He asked me this question.So i am giving you its solution what it is and how it works,a complete solution.

Happy Number -- A number is called happy if it leads to 1 after a sequence of steps where in each step number is replaced by sum of squares of its digit ie. if we start with Happy Number and keep replacing it with digits square sum, we reach 1.

Examples:

Input: n = 19
Output: True

19 is Happy Number,See how?

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

As we reached to 1, 19 is a Happy Number.

Input: n = 20
Output: False

A number will not be a Happy Number when it makes a loop in its sequence that is it touches a number in sequence which already been touched. So to check whether a number is happy or not, we can keep a set, if same number occurs again we flag result as not happy.

Sample Code implementation in Java:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class HappyNumberSolution
{
public static boolean isHappyNumber(int  n)
{
int slow=n,fast=n;

do
{
              slow = numSquareSum(slow);
     fast = numSquareSum(numSquareSum(fast));
}
while (slow!=fast);
 
return (slow==1);
}


       public static int numSquareSum(int n)
{
   int squareSum=0;
 
   while (n>0)
   {
    squareSum += (n % 10) * (n % 10);
       n /= 10;
}

return squareSum;
}

public static void main(String[] args)
{
int n = 13;  //20

   if (isHappyNumber(n))
     System.out.println(n+" is a Happy Number");
   else
    System.out.println(n+" is not a Happy Number");
}


}

Output:

1) 13 is a Happy Number(for input as 13).
2)20 is not a Happy Number(for input as 20)





Tuesday, October 18, 2016

Reverse an array or String in java

Question:

Write a program to reverse an array or string?.

Solution:(Recursively)

1) Initialize start and end indexes
start = 0, end = n-1
2) Swap arr[start] with arr[end]
3) Recursively call reverse for rest of the array.

Sample Code:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class ReverseArray
{
public static void reverse(int arr[],int start,int end)
{
int temp;
if(start>=end)
return;

temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
reverse(arr, start+1, end-1);
}

public static void printArray(int arr[], int size)
{
       for (int i=0; i < size; i++)
           System.out.print(arr[i] + " ");
       System.out.println("");
}

public static void main(String[] args)
{
    int arr[] = {1, 2, 3, 4, 5, 6};
            printArray(arr, 6);
            reverse(arr, 0, 5);
           System.out.println("Reversed array is ");
           printArray(arr, 6);
}
}


Output:

1 2 3 4 5 6
Reversed array is
6 5 4 3 2 1

Time Complexity: O(n)

Find Missing Number

Question:

You are given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in list. One of the integers is missing in the list.
Write an efficient code to find the missing integer.

Example:
Input:    [1, 2, 4, ,6, 3, 7, 8]
Output:    5

Solution:  There is a very simple sum formula for this solution.just have to use that formula.

Formula:

1. Get the sum of numbers
       total = (n+1)*(n+2)/2
2  Subtract all the numbers from sum and
   you will get the missing number.


Sample Code:
/**
 * @author Abhinaw.Tripathi
 *
 */
public class MissingNumber
{
public static int getMissingNo(int arr[],int n)
{
int total,i;
total=(n+1)*(n+2)/2;
for(i=0;i<n;i++)
total-=arr[i];
return total;
}
public static void main(String[] args)
{
int a[] = {1,2,4,5,6};
       int miss = getMissingNo(a,5);
      System.out.println("Missing Number is: "+miss);

}


}

Result: Missing Number is: 3

Time Complexity: O(n)

Note: There can be overflow if n is large. In order to avoid Integer Overflow, we can pick one number from known numbers and subtract one number from given numbers. This way we wont have Integer Overflow ever.
   
Will happen if we take n such that n(n+1)/2 > INT_MAX .



Monday, October 17, 2016

Heap Sort implementation in Java

Heap Sort:

Heap sort is a comparison based sorting technique based on Binary Heap Data-Structures.Now, What is Binary Heap?

Binary Heap is a complete Binary Tree in which every level is completely filled except possibly the last.So,A Binary Heap is a Complete Binary Tree where items are stored in a special order such that value in a parent node is greater(or smaller) than the values in its two children nodes. The former is called as max heap and the latter is called min heap. The heap can be represented by binary tree or array.

So Heap sort is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.

Now, again question comes why heap sort can be represented by binary tree or array?

Ans: Because, we all know,a Binary Heap is a Complete Binary Tree, it can be easily represented as array and array based representation is space efficient.

If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing starts at 0).

Heap Sort Algorithm for Sorting in Increasing Order:

1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.
3. Repeat above steps until size of heap is greater than 1.


Sample Code:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class HeapSortApp
{
public void sort(int arr[])
    {
        int n = arr.length;

        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        for (int i=n-1; i>=0; i--)
        {          
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            heapify(arr, i, 0);
        }
    }

   
    void heapify(int arr[], int n, int i)
    {
        int largest = i;  // Initialize largest as root
        int l = 2*i + 1;  // left = 2*i + 1
        int r = 2*i + 2;  // right = 2*i + 2

        // If left child is larger than root
        if (l < n && arr[l] > arr[largest])
            largest = l;

        // If right child is larger than largest so far
        if (r < n && arr[r] > arr[largest])
            largest = r;

        // If largest is not root
        if (largest != i)
        {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;
     
            heapify(arr, n, largest);
        }
    }

    /* A utility function to print array of size n */
    static void printArray(int arr[])
    {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i]+" ");
        System.out.println();
    }

public static void main(String[] args)
{
int arr[] = {12, 11, 13, 5, 6, 7};

        HeapSortApp ob = new HeapSortApp();
        ob.sort(arr);

        System.out.println("Sorted array is-->");
        printArray(arr);

}
}

Output: 

Sorted array is-->

5 6 7 11 12 13








Mobile Numeric Keypad Problem Solution in Java

Mobile Numeric Keypad Problem

Given the mobile numeric keypad. You can only press buttons that are up, left, right or down to the current button. You are not allowed to press bottom row corner buttons (i.e. * and # ).
Given a number N, find out the number of possible numbers of given length.

Examples:

For N=1, number of possible numbers would be 10 (0, 1, 2, 3, …., 9)
For N=2, number of possible numbers would be 36
Possible numbers: 00,08 11,12,14 22,21,23,25 and so on.
If we start with 0, valid numbers will be 00, 08 (count: 2)
If we start with 1, valid numbers will be 11, 12, 14 (count: 3)
If we start with 2, valid numbers will be 22, 21, 23,25 (count: 4)
If we start with 3, valid numbers will be 33, 32, 36 (count: 3)
If we start with 4, valid numbers will be 44,41,45,47 (count: 4)
If we start with 5, valid numbers will be 55,54,52,56,58 (count: 5)

Question is: We need to print the count of possible numbers.


Solution 1(Based on DFS):

N = 1 is trivial case, number of possible numbers would be 10 (0, 1, 2, 3, …., 9)
For N > 1, we need to start from some button, then move to any of the four direction (up, left, right or down) which takes to a valid button (should not go to *, #). Keep doing this until N length number is obtained (depth first traversal).

Solution 2(Recursive):

Mobile Keypad is a rectangular grid of 4X3 (4 rows and 3 columns)
Lets say Count(i, j, N) represents the count of N length numbers starting from position (i, j)

If N = 1
  Count(i, j, N) = 10
Else
  Count(i, j, N) = Sum of all Count(r, c, N-1) where (r, c) is new
                   position after valid move of length 1 from current
                   position (i, j)

Sample Code:

/************@Author : Abhinaw Tripathi*******************/

class IndexResult
{
int up,down,left,right;

public IndexResult()
{
up = down = left = right = -1;
}
}

public class KepadProblem
{

// check if given index is safe
static boolean isSafe(int i, int j)
{
return (i>=0 && i<3 && j>=0 && j<3);
}

// get set of indices in all 4 directions
static IndexResult getIndices(int n)
{
IndexResult result = new IndexResult();

// handle case for digit 0 separately
if(n == 0)
{
result.up = 8;

return result;
}

// get row and column of digit in 3*3 matrix
int row = n/3;
if(n%3 == 0)
row--;
int col = n - (row*3) - 1;

// set up index
if(isSafe(row-1,col))
result.up = (row-1)*3 + col + 1;

// set down index handling case for digit 8 separately
if(n == 8)
result.down = 0;
else
{
if(isSafe(row+1,col))
result.down = (row+1)*3 + col + 1;
}

if(isSafe(row,col-1))
result.left = row*3 + col;

if(isSafe(row,col+1))
result.right = row*3 + col + 2;

return  result;
}

static int getCount(int N)
{
int[][] mat = new int[10][N];

for(int j=0;j<N;j++)
{
for(int i=0;i<=9;i++)
{
if(j == 0)
mat[i][j] = 1;
else
{
// get set of indices in all 4 directions in "result"
IndexResult result = getIndices(i);

mat[i][j] = mat[i][j-1];
if(result.up != -1)
mat[i][j] += mat[result.up][j-1];
if(result.down != -1)
mat[i][j] += mat[result.down][j-1];
if(result.left != -1)
mat[i][j] += mat[result.left][j-1];
if(result.right != -1)
mat[i][j] += mat[result.right][j-1];
}
}
}

// sum of answers for length N for all starting digits
int sum = 0;
for(int i=0;i<=9;i++)
sum += mat[i][N-1];

return sum;
}

public static void main(String[] args)
{
int N = 5;
System.out.println("N = " + N);
System.out.println("\nAns = " + getCount(N));
}
}

OutPut: 

N = 5
Ans = 2062
 

Tuesday, September 20, 2016

Send Email and Attache Text or Image file in Java tutorial

I am going to give you a brief about how it send email in java programs. Sending emails is one of the common tasks in real life applications and that’s why Java provides robust JavaMail API that we can use to send emails using SMTP server. JavaMail API supports both TLS and SSL authentication for sending emails.

we will learn how to use JavaMail API to send emails using SMTP server with no authentication, TLS and SSL authentication and how to send attachments and attach and use images in the email body. For TLS and SSL authentication, I am using GMail SMTP server because it supports both of them.

JavaMail API is not part of standard JDK, so you will have to download it from it’s official website i.e JavaMail Home Page. Download the latest version of the JavaMail reference implementation and include it in your project build path. The jar file name will be javax.mail.jar.

If you are using Maven based project, just add below dependency in your project.

<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>

1)Creating javax.mail.Session object

2)Creating javax.mail.internet.MimeMessage object, we have to set different properties in this object such as recipient email address, Email Subject, Reply-To email, email body, attachments etc.

3)Using javax.mail.Transport to send the email message.

The logic to create session differs based on the type of SMTP server, for example if SMTP server doesn’t require any authentication we can create the Session object with some simple properties whereas if it requires TLS or SSL authentication, then logic to create will differ.

So I will create a utility class with some utility methods to send emails and then I will use this utility method with different SMTP servers.

Here is the sample code:

EmailUtil.java:

import java.io.UnsupportedEncodingException;
import java.util.Date;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;
/**
 * @author Abhinaw.Tripathi
 *
 */
public class EmailUtil
{
/**
* Utility method to send simple HTML email
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
   {
     MimeMessage msg = new MimeMessage(session);
     //set message headers
     msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
     msg.addHeader("format", "flowed");
     msg.addHeader("Content-Transfer-Encoding", "8bit");
     msg.setFrom(new InternetAddress("Abhinaw. Tripathi@igt.com", "NoReply-JD"));
     msg.setReplyTo(InternetAddress.parse("abhinawtripathi34@gmail.com", false));
     msg.setSubject(subject, "UTF-8");
     msg.setText(body, "UTF-8");
     msg.setSentDate(new Date());
     msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
     System.out.println("Message is ready");
         Transport.send(msg);
     System.out.println("EMail Sent Successfully!!");
   }
   catch (Exception e)
{
     e.printStackTrace();
   }
}
/**
* Utility method to send email with attachment
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendAttachmentEmail(Session session, String toEmail, String subject, String body)
{
try
{
        MimeMessage msg = new MimeMessage(session);
        msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");  
    msg.setFrom(new InternetAddress("Abhinaw.Tripathi@igt.com", "NoReply-JD"));
    msg.setReplyTo(InternetAddress.parse("abhinawtripathi34@gmail.com", false));
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));    
        // Create the message body part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Fill the message
        messageBodyPart.setText(body);
        // Create a multipart message for attachment
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Second part is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "abc.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
        // Send the complete message parts
        msg.setContent(multipart);
        // Send message
        Transport.send(msg);
        System.out.println("EMail Sent Successfully with attachment!!");
     }
catch (MessagingException e)
{
        e.printStackTrace();
   }
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}

/**
* Utility method to send image in email body
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendImageEmail(Session session, String toEmail, String subject, String body)
{
try
{
        MimeMessage msg = new MimeMessage(session);
        msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");    
    msg.setFrom(new InternetAddress("Abhinaw.Tripathi@igt.com", "NoReply-JD"));
    msg.setReplyTo(InternetAddress.parse("abhinawtripathi34@gmail.com", false));
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));    
        // Create the message body part
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);      
        // Create a multipart message for attachment
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Second part is image attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "image.png";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        //Trick is to add the content-id header here
        messageBodyPart.setHeader("Content-ID", "image_id");
        multipart.addBodyPart(messageBodyPart);
        //third part for displaying image in the email body
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent("<h1>Attached Image</h1>" +"<img src='cid:image_id'>", "text/html");
        multipart.addBodyPart(messageBodyPart);      
        //Set the multipart message to the email message
        msg.setContent(multipart);
        // Send message
        Transport.send(msg);
        System.out.println("EMail Sent Successfully with image!!");
     }
catch (MessagingException e)
{
        e.printStackTrace();
   }
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}


Now if you wish to send simple email do something like this:

SimpleEmail.java:

import java.util.Properties;
import javax.mail.Session;
/**
 * @author Abhinaw.Tripathi
 *
 */
public class SimpleEmail
{
   public static void main(String[] args)
   {
   System.out.println("SimpleEmail Start");
   String smtpHostServer = "smtp.gmail.com";
   String emailID = "abhinawtripathi34@gmail.com";
   Properties props = System.getProperties();
   props.put("mail.smtp.host", smtpHostServer);
   Session session = Session.getInstance(props, null);
   EmailUtil.sendEmail(session, emailID,"SimpleEmail Testing Subject", "SimpleEmail Testing Body");
   }
 

}

if  you wish to send email with SSL Authentication do something like this:

SSLEmail.Java:

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

public class SSLEmail
{
/**
  Outgoing Mail (SMTP) Server
  requires TLS or SSL: smtp.gmail.com (use authentication)
  Use Authentication: Yes
  Port for SSL: 465
*/
public static void main(String[] args)
{
final String fromEmail = "myemailid@gmail.com"; //requires valid gmail id
final String password = "mypassword"; // correct password for gmail id
final String toEmail = "myemail@yahoo.com"; // can be any email id

System.out.println("SSLEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port

Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};

Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
       EmailUtil.sendEmail(session, toEmail,"SSLEmail Testing Subject", "SSLEmail Testing Body");
       EmailUtil.sendAttachmentEmail(session, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");
       EmailUtil.sendImageEmail(session, toEmail,"SSLEmail Testing Subject with Image", "SSLEmail Testing Body with Image");
}


}

TLSEmail.java:

/**
 * 
 */
package com.advanceemail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
/**
 * @author Abhinaw.Tripathi
 *
 */
public class TLSEmail 
{
/**
  Outgoing Mail (SMTP) Server
  requires TLS or SSL: smtp.gmail.com (use authentication)
  Use Authentication: Yes
  Port for TLS/STARTTLS: 587
*/
public static void main(String[] args)
{
final String fromEmail = "myemailid@gmail.com"; //requires valid gmail id
final String password = "mypassword"; // correct password for gmail id
final String toEmail = "myemail@yahoo.com"; // can be any email id 
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
       //create Authenticator object to pass in Session.getInstance argument
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() 
{
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getInstance(props, auth);
EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject", "TLSEmail Testing Body");
}
}



In above all code i have shown you how to send email .however you can also attache text file and image file also.very simple code.in fact you can also design the email in HTML format.