Email for failing Selenium Script ‘s Stack Trace to your Email Id

In this post, we would be learning how to send Email for failing Selenium Script which includes all the stack trace. For this, we would be using Java Mail API and In one of the post we have written a detailed post about uses of JavaMail API, So if you want to read the post then read it
Reading e-mail using Javamail api
1- Pre-requisite
First, we need to download two jar files
1- javaee-api-5.0.3.jar
2- javamail1_4_7.zip
download both file from here
[the_ad_placement id=”incontent”]
In this Java Mail API we use mainly two packages
1) javax.mail.internet.
2) javax.mail

In general we use three steps to send emails using JavaMail API

1- Session Object creation that stores all the information like Hostname, username and password
like this

Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("usermail_id","password");
}
})

 

2- Setting Subject and Message body like this

message.setSubject("Testing Subject"); //this line is used for setting Subject line

message.setText("your test has failed <============================>"+ExceptionUtils.getStackTrace(e) );

 

3- Sending mail that could be done with this line of code

Transport.send(message);

 

[the_ad_placement id=”incontent”]

2- Now I am posting here my code of Mail sending class

package test_Scripts;
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.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class SendMail{
public SendMail(String fromMail,String tomail, Exception e )
{
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");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("Email_Id","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromMail));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(tomail));
message.setSubject("Script failed");
message.setText("your test has failed for script name:Name of your scipt <============================>"+ ExceptionUtils.getStackTrace(e) );
Transport.send(message);
System.out.println("Done");
} catch (MessagingException ex) {
throw new RuntimeException(ex);
}
}
}

 

 

I have written one class SendMail with one constructor with three parameters. that I would call in my WebDriver script. and When My code would fail somewhere then It will send the Stack Trace.

3- My script of WebDriver

package test_Scripts;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class Except {
WebDriver d;
@BeforeMethod
public void launch()
{
System.setProperty("webdriver.chrome.driver", "E:\DD MISHRA\workspace\chromedriver_win_26.0.1383.0\chromedriver.exe");
d = new ChromeDriver();
}
@Test
public void test()
{
d.get("www.gmail.com");
try{
WebElement element= d.findElement(By.xpath("//div/span"));
element.sendKeys("dwarika");
}
catch(Exception e)
{
e.printStackTrace();
new SendMail("Sender_Mailid","Receiver_Mailid",e);
}
}
}

 

I have tried it to send an email for failing Selenium Script. So hope you also enjoy this post . would be very happy if you share your advice to optimize this code.

 

 

Dwarika Dhish Mishra

My name is Dwarika Dhish Mishra, its just my name and I am trying to bring the worth of my name in to actions and wants to be the solution not the problem. I believe in spreading knowledge and happiness. More over I am fun loving person and like travelling a lot. By nature I am a tester and a solution maker. I believe in the tag line of http://ted.org “Idea worth spreading” . For the same, I have created this blog to bring more and more learning to tester fraternity through day to day learning in professional and personal life. All contents are the part of my learning and so are available for all..So please spread the contents as much as you can at your end so that it could reach to every needful people in testing fraternity. I am pretty happy that more and more people are showing interest to become the part your Abode QA blog and I think this is good sign for us all because more and more content would be before you to read and to cherish. You may write or call me at my Email id: dwarika1987@gmail.com Cell: 9999978609

You may also like...

23 Responses

  1. Raghuveer says:

    Hey Great Job It worked for me thanks a ton i was working on this from a week…

  2. Razen says:

    Great Job, it worked for me too 🙂
    Thanks a lot.

  3. @Rahim

    Please go through the both classes and might be you would find the answer to your question at your own.

  4. How to use this code to send email from my outlook? plz help

    • Use this information

      Outlook.com SMTP server address: smtp.live.com
      in place of “smtp.gmail.com”
      and
      Outlook.com SMTP port: 587 in place of 465.

      Use this information in the code and it will work for you !!!
      If you are trying this code for outlook.com

  5. biswajit says:

    Hi ,
    thanks for this details, but could not able to locate where exactly changes need to be required to get the test report mail..

  6. biswajit says:

    Finally I am able to send the fail test in mail.

    Thanks for your help and support friend
    Biswajit samal

  7. Janet Frank says:

    Can you show the whole program. I am trying to do this but having some issues. I am using the NetBeans IDE to develop the Junit4 code.

    • I don’t think that any problem should creep in to above code.

      Above code is well tested in Eclipse IDE and all code is present in the post so please go through the above code once again or if even after that you need assistance then you may ping me any time at my skype id dwarika.dhish.mishra

      • Janet Frank says:

        When I try to run the Selenium test I get an error that there is no main class. What am I doing wrong??

        • In this case might be you are missing some annotations of Junit then other wise in presence of Junit annotation for Junit 4 or testMethod name is sufficient to run the code withough asking for main method.

          So can you share your script.

      • Janet Frank says:

        Here is the selenium code:

        /*
        * To change this license header, choose License Headers in Project Properties.
        * To change this template file, choose Tools | Templates
        * and open the template in the editor.
        */

        import java.util.concurrent.TimeUnit;
        import org.junit.*;
        import static org.junit.Assert.*;
        import org.openqa.selenium.By;
        import org.openqa.selenium.WebDriver;
        import org.openqa.selenium.firefox.FirefoxDriver;

        /**
        *
        * @author jfrank1
        */
        public class Webdrivertest2Test {

        private WebDriver driver;
        private String baseUrl;
        private boolean acceptNextAlert = true;
        private StringBuffer verificationErrors = new StringBuffer();

        public Webdrivertest2Test() {
        }

        @BeforeClass
        public static void setUpClass() {
        System.out.println(“setUp”);
        Webdrivertest2 instance = new Webdrivertest2();
        instance.setUp();
        // TODO review the generated test code and remove the default call to fail.
        fail(“The test case is a prototype.”);
        }

        @AfterClass
        public static void tearDownClass() {
        System.out.println(“tearDown”);
        Webdrivertest2 instance = new Webdrivertest2();
        instance.tearDown();
        // TODO review the generated test code and remove the default call to fail.
        fail(“The test case is a prototype.”);
        }

        /**
        * Test of setUp method, of class Webdrivertest2.
        */

        @Test
        public void testWebdriverTest() throws Exception {
        driver = new FirefoxDriver();
        baseUrl = “http://stage7.bicycling.com”;
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get(baseUrl + “/”);
        try {
        driver.findElement(By.linkText(“Subscrib”)).click();
        }
        catch (Exception e) {
        new SendMail(“janet.frank@rodale.com”,”janet.frank@rodale.com”,”ZAD-TEST”,”testing error email”);
        }
        driver.findElement(By.linkText(“Give a Gift”)).click();
        // TODO review the generated test code and remove the default call to fail.
        fail(“The test case is a prototype.”);
        }

        Here is the email class that I add to the project. I Know this code works as standalone but cannot get my script to run in Netbeans 7.4. Not sure what I am doing wrong but it keep telling met there is no “main” class. Please understand that it has been 13 years since I coded in Java so I am VERY rusty:

        /*
        * To change this license header, choose License Headers in Project Properties.
        * To change this template file, choose Tools | Templates
        * and open the template in the editor.
        */

        /**
        *
        * @author jfrank1
        */

        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.InternetAddress;
        import javax.mail.internet.MimeMessage;
        import org.apache.commons.lang3.exception.ExceptionUtils;

        public class SendMail {
        public SendMail(String fromMail,String tomail, String subject, String msg )
        {
        Properties props = new Properties();
        props.put(“mail.smtp.host”, “smtp.rodale.com”);
        props.put(“mail.smtp.socketFactory.port”, “25”);
        props.put(“mail.smtp.socketFactory.class”,
        “javax.net.ssl.SSLSocketFactory”);
        props.put(“mail.smtp.auth”, “true”);
        props.put(“mail.smtp.port”, “25”);
        Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(“janet.frank@rodale.com”,”Annie909!”);
        }
        });
        try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromMail));
        message.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse(tomail));
        message.setSubject(subject);
        message.setText(“your test has failed for script name: “+ msg );
        Transport.send(message);
        System.out.println(“Done”);
        } catch (MessagingException ex) {
        throw new RuntimeException(ex);
        }
        }
        }

  8. Janet Frank says:

    I am not sure why I cannot get it to run in NetBeans but it does work in Eclipse. Now how do you get this all put together so that you can schedule it to run at a certain time??

  9. pavan says:

    Hi
    can any body tell me how to run more than 1000 test cases at a time

  10. archana says:

    Awesome BlogPost !!!
    Thanks alot..

  11. archana says:

    How can i send success report as well…

  12. Pankti Shah says:

    Thank you so much for the details. However; this will send email for each failed script; How can I send single email for total failed script with failed method names ? TIA

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.