Monday, April 9, 2012

Sending the mail with Attachment using java

everyone like to send the reports after excuting the test. here you will found one way using java.

In my case, There are multiple HTML reports will generate after excuting the selenium scripts. so, first thing i have to do is Zip the folder and send to the mail with that zip file to the Manager. i hope below code is very helpfull if u have same situation.

Zip the Folder:-

package poc.Tasks;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class zipfile {
//we need to pass to Argments, 1. Destination Folder Path, 2. Source Directory Path
    public static void zipfolder(String Destloc, String sourceLoc ){
    try
    {
    //create a ZipOutputStream to zip the data to
    ZipOutputStream zos = new
    ZipOutputStream(new FileOutputStream(Destloc+".zip"));
    //assuming that there is a directory named inFolder (If there
    //isn't create one) in the same directory as the one the code
    //runs from,
    //call the zipDir method
    zipDir(sourceLoc, zos);
    //close the stream
    zos.close();
    }
    catch(Exception e)
    {
    //handle exception
    }
    }
    //here is the code for the method
    public static void zipDir(String dir2zip, ZipOutputStream zos)
    {
    try
    {
    //create a new File object based on the directory we
    //have to zip File
    File zipDir = new File(dir2zip);
    //get a listing of the directory content
    String[] dirList = zipDir.list();
    byte[] readBuffer = new byte[2156];
    int bytesIn = 0;
    //loop through dirList, and zip the files
    for(int i=0; i<dirList.length; i++)
    {
    File f = new File(zipDir, dirList[i]);
    if(f.isDirectory())
    {
    //if the File object is a directory, call this
    //function again to add its content recursively
    String filePath = f.getPath();
    zipDir(filePath, zos);
    //loop again
    continue;
    }
    //if we reached here, the File object f was not
    //a directory
    //create a FileInputStream on top of f
    FileInputStream fis = new FileInputStream(f);
    //create a new zip entry
    ZipEntry anEntry = new ZipEntry(f.getPath());
    //place the zip entry in the ZipOutputStream object
    zos.putNextEntry(anEntry);
    //now write the content of the file to the ZipOutputStream
    while((bytesIn = fis.read(readBuffer)) != -1)
    {
    zos.write(readBuffer, 0, bytesIn);
    }
    //close the Stream
    fis.close();
   }
    System.out.println("Ziping Folder is Done");

    }
    catch(Exception e)
    {
    System.out.println("Exception in Ziping the folder");
    }

}}


Sending Mail with an Attachment:-

here the code for the Sending the mail with Attachment.


import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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 javamail{
  public static Boolean sendmailAttachment(String args,String msg, String to)
      throws Exception {
 
      String fileAttachment = args;
   // Get system properties
   // Properties props = System.getProperties();
      Properties props = new Properties();
    // Setup mail server
      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");
   // Get session
      Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                 protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication("UserName","Password");
                 }});
      try {
    // Define message
    Message message = new MimeMessage(session);
     
       message.setFrom(new InternetAddress("UR Mail ID"));
       message.setRecipients(Message.RecipientType.TO,
         InternetAddress.parse(to));
       message.setSubject("Mail Subject");
       message.setText(msg);
   
   

    // create the message part
    MimeBodyPart messageBodyPart =new MimeBodyPart();

    //fill message
    messageBodyPart.setText("Dear All, \n\n\tab\tab Please find Automation Report \n Regards \n Seshu");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // Part two is attachment
    messageBodyPart = new MimeBodyPart();
    DataSource source =
      new FileDataSource(fileAttachment);
    messageBodyPart.setDataHandler(
      new DataHandler(source));
    messageBodyPart.setFileName(fileAttachment);
    multipart.addBodyPart(messageBodyPart);

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

    // Send the message
    Transport.send( message );
    System.out.println("Message sent");
  } catch (MessagingException e) {
       e.printStackTrace();
       System.out.println("exception in Send Mail");
       return false;
      }
      return true;
     }
  public static void main(String args[]) throws Exception
  {
sendmailAttachment("Zip Folder Path","Mail With Attachment","Destination Mail ID");
  }
}

if anybody have problem with the code , plz get back to me.