Automatically Email the reports after Selenium test execution
RSSS

How to automatically trigger email with reports after execution ?

There might be situations, where you might be tasked by the management people or your clients to send email after your every test execution. Here is a solution for that

This post exclusively written as requested by one of our fellow readers of this blog :)

In this post we are going to look how we can send email to the clients
or stakeholders after the selenium test execution has been completed.

The program which we need include in Selenium Framework is,
Download here the Mail.jar
Download here the activation.jar

//The jar files which I have used are activation.jar and mail.jar Can be downloaded from Internet.

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

 public class SendMail

{
    //reportFileName = TestExecutionResultFileName
    public static void execute(String reportFileName) throws Exception

    {
        String path=<Report file path>;

        String[] to={"<stakeholder1>","<stakeholder2>"};
        String[] cc={};
        String[] bcc={"<AutomationTester>"};

        SendMail.sendMail("<AutomationTesterUserName>",
                            "<AutomationTesterPassword>",
                            "smtp.gmail.com",
                            "465",
                            "true",
                            "true",
                             true,
                            "javax.net.ssl.SSLSocketFactory",
                            "false",
                             to,
                             cc,
                             bcc,
                            "<Subject line>",
                            "<Contents if any>",
                            path,
                            reportFileName);
      }

      public  static boolean sendMail(String userName,
                String passWord,
                String host,
                String port,
                String starttls,
                String auth,
                boolean debug,
                String socketFactoryClass,
                String fallback,
                String[] to,
                String[] cc,
                String[] bcc,
                String subject,
                String text,
                String attachmentPath,
                String attachmentName){

        //Object Instantiation of a properties file.
        Properties props = new Properties();

        props.put("mail.smtp.user", userName);

        props.put("mail.smtp.host", host);

        if(!"".equals(port)){
        props.put("mail.smtp.port", port);
        }

        if(!"".equals(starttls)){
            props.put("mail.smtp.starttls.enable",starttls);
            props.put("mail.smtp.auth", auth);
        }

        if(debug){

        props.put("mail.smtp.debug", "true");

        }else{

        props.put("mail.smtp.debug", "false");

        }

        if(!"".equals(port)){
            props.put("mail.smtp.socketFactory.port", port);
        }
        if(!"".equals(socketFactoryClass)){
            props.put("mail.smtp.socketFactory.class",socketFactoryClass);
        }
        if(!"".equals(fallback)){
            props.put("mail.smtp.socketFactory.fallback", fallback);
        }

        try{

            Session session = Session.getDefaultInstance(props, null);

            session.setDebug(debug);

            MimeMessage msg = new MimeMessage(session);

            msg.setText(text);

            msg.setSubject(subject);

            Multipart multipart = new MimeMultipart();
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachmentPath);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachmentName);
            multipart.addBodyPart(messageBodyPart);

            msg.setContent(multipart);
            msg.setFrom(new InternetAddress(userName));

            for(int i=0;i<to.length;i++){
                msg.addRecipient(Message.RecipientType.TO, new
InternetAddress(to[i]));
            }

            for(int i=0;i<cc.length;i++){
                msg.addRecipient(Message.RecipientType.CC, new
InternetAddress(cc[i]));
            }

            for(int i=0;i<bcc.length;i++){
                msg.addRecipient(Message.RecipientType.BCC, new
InternetAddress(bcc[i]));
            }

            msg.saveChanges();

            Transport transport = session.getTransport("smtp");

            transport.connect(host, userName, passWord);

            transport.sendMessage(msg, msg.getAllRecipients());

            transport.close();

            return true;

        } catch (Exception mex){
            mex.printStackTrace();
            return false;
        }
    }
}

The above Source code will do the job of triggering email after every execution.


Where to how to use it?


Add the below snippet at the end of the test execution report creation.


SendMail.execute(ExecutionFileName);

With this the whole setup of automatic email triggering functionality is integrated with our framework.

43 thoughts on “Automatically Email the reports after Selenium test execution

  1. Kristal Asbury
    November 16, 2012 at 12:09 am

    I didnt look for this, but I like this, found it enlightening! Keep up the great work!

    1. November 16, 2012 at 9:07 am

      Cool. I am glad that it helps you.

      1. Abhay Pratap
        January 17, 2014 at 1:11 pm

        At a time i am only able to either send attachment or body text from the above code.

        as,
        if i comment out “//msg.setText(text);”, it sends out email with attachment.
        and
        and if i uncomment the above line, it only sends out email with body text and no attachment.

        Can anyone help me with some insight, so as what needs to be done to have an email with both body and attachment.

        Thanks

        1. Rakesh
          August 11, 2014 at 1:32 pm

          Hi,Just create MimeBodyPart messageBodyPart1 = new MimeBodyPart(); instance

          messageBodyPart1.setText(“Hi All,\nPlease find the Automation Batch Execution Results in attachement.\n”
          + “=======\n”
          +”\n\nThanks and Regards,\nQA Automation Team”);

          multipart.addBodyPart(messageBodyPart2, 0);

          the above code anyhow will give you an attachment,It works for me

  2. shashi
    November 16, 2012 at 5:16 pm

    NICE one and much required topic for me

    1. November 20, 2012 at 10:01 am

      Glad to see that my blog is posted on the official Selenium blog.

  3. satish
    November 20, 2012 at 6:52 pm

    Please specify the path where can i get the above activation.jar and internet.jar files

    1. November 20, 2012 at 11:21 pm

      Sathish,
      Thanks for pointing it out. I have updated the post with url to download.

  4. satish
    November 22, 2012 at 2:32 am

    Hi
    In the above code for this “String path=” What we need to give the “Report File path”
    And In this command “SendMail.execute(Execution File Name)” What we need to give the “Execution File Name”

    Please clarify above 2 things ,this would helpful to understand .

    Regards,
    Satish.M

    1. November 22, 2012 at 12:00 pm

      String path = (Just mention the path where your reports are generated at your local machine. eg: C:/seleniumworkspace/reports)

      SendMail.execute(Just specify the file name of the report created for the corresponding test execution)
      for eg. consider a report is generated for a test execution. This report will be located in C:/seleniumworkspace/reports/testcase1.html)
      In this case, the method we need to mention will be : SendMail.execute(testcase1.html)

      1. sriharsha
        September 23, 2013 at 5:56 am

        Hi asswertselenium , thanks for the code but am facing a problem , I have a test script where at the end I have to run this emailing . But my reports are generated using testng and the final report comes here as “emailalble report.html” but when I tried to give the same in Sendmail.execute(emailable-report.html); it is throwing error . please help me out .

        1. ck
          September 25, 2013 at 3:50 am

          Hey Sriharsha,

          I’m having the exact same issue as you with testng and emailable-report, did you manage to get around this?

        2. Max
          October 15, 2014 at 6:36 pm

          Hi Sri,

          Did u got the solution for this error??
          Even i too have same…

  5. Umamaheshwar Thota
    January 11, 2013 at 3:20 pm

    Thanks assertselenium, it helped me a lot.

    1. January 11, 2013 at 6:20 pm

      welcome Umamaheshwa. Keep visiting.

  6. Nishanth
    February 18, 2013 at 12:43 pm

    i am getting this error “javax.mail.AuthenticationFailedException”…and also it says as “535-5.7.1 Username and Password not accepted. Learn more at 535 5.7.1 http://support.google.com/mail/bin/answer.py?answer=14257 d1sm66357567paz.17 – gsmtp”…
    i have mentioned my username and password correctly..but still it shows tis error….

  7. Navjot Kaur
    March 19, 2013 at 1:35 pm

    Hi Manoj,

    Nice Blog.I am trying to send report from gmail id to yahoo id by using above code. Subject and attachments are coming in yahoomail id. But message text is not coming.My testscript has run successfully.Please look at this issue.Thanks in advance..

  8. March 19, 2013 at 1:36 pm

    Hi Manoj,

    Nice Blog.I am trying to send report from gmail id to yahoo id by using above code. Subject and attachments are coming in yahoomail id. But message text is not coming.My testscript has run successfully.Please look at this issue.Thanks in advance

  9. March 24, 2013 at 8:09 pm

    error throwed like system cannot find the path

    my file is in D:email-report

    i gave path as “D:”

    passed string is “email-report”

  10. ArvindRedy
    May 2, 2013 at 12:25 pm

    Hey it worked for me, Thankyou very much :)

  11. Hariharan
    May 16, 2013 at 2:14 pm

    Superb, It works for me..

    Thanks Manoj

    1. May 16, 2013 at 5:50 pm

      I am happy for you.

  12. June 7, 2013 at 4:58 am

    Good Work Manoj………… Code really works!!!!!!!!!!!!!

    Keep up the good work… i really like it

    1. Raghu
      August 19, 2013 at 8:23 am

      Hi Can you post the working code please i am seeing lot many errors when i created a class with the above code , Do i need to import some jar files apart from mail.jar and activation.jar

  13. Naveen
    June 27, 2013 at 11:32 am

    Hi assertselenium,

    The text and BCC doesn’t populate value in the email i.e. triggered on executing this code? Please assist.

  14. Lynn
    July 1, 2013 at 9:38 am

    I got the following error javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect

    Any idea?

  15. shama
    July 2, 2013 at 12:38 pm

    hello,

    I have used this code in my project, i did not get any error , but the mail is never sent. Could you plz tell me where must be the problem.

    Thanks and regards,
    Shama Ugale

  16. Manish
    August 13, 2013 at 8:45 am

    Will it work for testng report ?

  17. Amit
    September 18, 2013 at 7:08 am

    Hi Manoj,
    It is a nice post and is very helpfull to all. I have a doubt that I am creating a framework in selenium and I a, using the dataProvider technique for getting data from excel sheet. But I want to ask that do I need to keep a already created java file called “ExcelHandler.java” (which is created for reading excel sheet having all methods to read excel) in my framework or not. Or can I use this dataprovider approach in my framework to read data from excel sheet.
    Kindly suggest on this.

    1. September 19, 2013 at 6:37 am

      You can try porting the existing ExcelHandler.java as a value to the dataprovider.

  18. Amit
    September 19, 2013 at 9:25 am

    Hi Manoj,
    Thanks for quick reply. I am using Excel_Handler (a extra class) for reading excel sheets and below is my code for DataProvider which I have kept in a separate package:-
    @DataProvider
    public static Object[][] ValidnameProvider(ITestContext context) throws Exception
    {
    String ExcelPath = context.getCurrentXmlTest().getParameter(“path”);
    File file = new File(ExcelPath);
    ExcelHandler Excel = new ExcelHandler(file);
    //ExcelHandler Excel=new ExcelHandler(new File(Excelpath));
    Excel.selectSheet(“Registration”);
    String Name = Excel.getColumn(4, true).get(11).getContents();
    return new Object[][]{{Name}};
    }

    Here I am fetching only one row data for one field from the excel. But now my question is how can I get the username/password simultaneously from the excel sheet.

    kindly help me here to get data for two fields. Your help would be really appreciated.

    Thanks

  19. Amit
    September 24, 2013 at 12:35 pm

    Hi,
    I have created a method to select a dropdown value automatically. Then i am calling this method in main function but its not selecting the value in the drop down. Can you help e here that why its not selecting the value from the drop down. Am I doing anything wrong here.
    This is the method for selecting the dropdown value:-
    public static void setComboBoxValue(WebElement selectElement, String listName){
    List optionlist = selectElement.findElements(By.tagName(“option”));
    for(WebElement optionelement : optionlist){
    if(optionelement.getText().equalsIgnoreCase(listName)){
    optionelement.click();
    break;
    }
    }
    }

    ———————–
    Below is the main method where I am calling the above dropdown selection method:-
    public static void main(String[] args) throws InterruptedException{
    String val = null;
    driver = new FirefoxDriver();
    driver.get(“any site”);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    WebElement drpVal = driver.findElement(By.id(“Type_Loan”));
    setComboBoxValue(drpVal, val);
    }

    But its not selecting the value from the dropdown.

    Kindly help

  20. Lavkesh Rajput
    October 6, 2013 at 10:17 am

    Hi ,

    I am getting error in below code.

    for(int i=0;i<to.length;i++){
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
    }

    could you please explain what will be put at “i&lt” place in above code.

    thanks in advance.

    1. October 6, 2013 at 11:52 am

      Hi Lavkesh,

      It was some formatting errors. Have updated now, check the same.

      Regards,
      Manoj

  21. surya
    December 10, 2013 at 6:36 am

    Hi Manoj,

    i get following message. can u please help out?

    java.io.FileNotFoundException: F:\Test Scripts\ (Access is denied)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.(Unknown Source)
    at javax.activation.FileDataSource.getInputStream(Unknown Source)
    at javax.activation.DataHandler.writeTo(Unknown Source)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1147)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:668)
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:233)
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:67)

    1. shilpa
      December 12, 2013 at 1:00 pm

      Hi,

      The code worked perfectly fine for me. I was just looking for this in many sites.
      However i want to now send a report file which is inside folder dated current date and time. This folder is created by build.xml using

      How can i pass this value in path?

      How can i get the out directory path from build.xml into java file?

  22. Ade
    March 25, 2014 at 3:28 pm

    Nice idea. How can I implement this in C# with webdriver API?

  23. kathir
    March 27, 2014 at 11:43 am

    in which class we need to add SendMail.execute(ExecutionFileName).
    please explain me…

  24. Shawn
    July 30, 2014 at 7:43 am

    Thanks a lot~

  25. balaji
    September 8, 2014 at 10:33 am

    hi am new to selenium webdriver and i have a situation that check all the websites are working properly from excel sheet and reporting to the specified mail id

  26. balaji
    September 23, 2014 at 7:36 am

    hi am new to automation, could you assist me how to generate reports in selenium webdriver

  27. jagadeesan
    October 29, 2014 at 11:49 am

    hi assertselinum,
    I have few doubts,i am running the selenium script in Eclipse ,
    I want to mail the results of scripts.
    I couldn’t find the path where reports are generated at your local machine

Leave a Reply

Your email address will not be published. Required fields are marked *