Send Email For Failed Step In Selenium

Send Email Failed Step

Imagine you have a large automation suite which executes at night at some scheduled time. Skimming through the failed scripts would be a nightmare in the morning. However, Javax mail API make things easier as it could be used to send email for failed step in selenium. You may download the jar from HERE

In addition to the above jar, we will use a class SendEmail which is a standard class and can be found over the internet. You are only required to change few field values (mentioned in the code) and it would send a customized email for failed step.

Let’s try to perform the following steps and send an email upon step failure.

  • Open a browser (preferably chrome) and navigate to https://www.facebook.com/
  • Enter values in Email and Password fields.
  • Deliberately use the wrong locator for Log In button and try to click it.
  • Send an email with customized email text and subject, from one email address to another email address(es)

Do not worry if your OS warns you for suspicious file while downloading the jar file. Every jar file is treated as potential risk.

Setup Project In Eclipse

Visit THIS link to learn how to create a new Java project, associate selenium jars and configure ChromeDriver. Once the project is created, associate the mail.jar in the same way selenium jars are associated.

Create a package screenshotEmail inside this project and create the following two classes:

  • ScreenshotEmailTest – This class would contain the script to interact with the application under test. This class contains the main method.
  • SendEmail – This is the already available class which contains the logic to send an email. We will use the reference of this class in the above class to send email for failed step.

SendEmail.java

Copy and paste below code to the SendEmail.java class. Fields which should be changed are highlighted in bold:

 

package screenshotEmail;


    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    import java.io.*;

    /*
      You need to change only following constant values

        SMTP_HOST_NAME 
        SMTP_AUTH_USER 
        SMTP_AUTH_PWD  

      

      emailMsgTxt  
      emailSubjectTxt  
      emailFromAddress 

      emailList -  This String array contains all email addresses where user wish to send the email.


      Create object of this class as follows in the calling class, ScreenshotEmailTest in this case

     SendEmail email = new SendEmail();

    */

    public class SendEmail
    {

      public static final String SMTP_HOST_NAME = "smtp.gmail.com";
      public static final String SMTP_AUTH_USER = "appliedselenium@gmail.com";
      public static final String SMTP_AUTH_PWD  = "YOUR PASSWORD OF ABOVE GMAIL ACCOUNT"; 
      
      

      public static final String emailMsgTxt      = "Error found while clicking on an element";
      public static final String emailSubjectTxt  = "Error Message From Selenium WebDriver";
      public static final String emailFromAddress = "appliedselenium@gmail.com";

      // Add List of Email address where user wish to send the email 
      public static final String[] emailList = {"dhawalkjoshi@gmail.com"};
    
      public void postMail( String recipients[ ], String subject,
                                String message , String from) throws MessagingException
      {
        boolean debug = false;

         //Set the host smtp address
         Properties props = new Properties();
         props.put("mail.smtp.starttls.enable", "true");
         props.put("mail.smtp.host", SMTP_HOST_NAME);
         props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);

        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

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


        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        
        Transport.send(msg);
        System.out.println("Sucessfully Sent mail to All Users");
     }


    /**
    * SimpleAuthenticator is used to do simple authentication
    * when the SMTP server requires it.
    */
    private class SMTPAuthenticator extends javax.mail.Authenticator
    {

        public PasswordAuthentication getPasswordAuthentication()
        {
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }

    }


    



ScreenshotEmailTest.java

This class contains the script to automate the test steps. It also contains the object reference of SendEmail class and using this object we will call the postMail method which is used to send email for failed step.

We will also take the screenshot of failed test step and this is a task for you to modify the code and send this file as an attachment in the email.

 

 

package screenshotEmail;

import java.io.File;
import java.io.IOException;

import javax.mail.MessagingException;

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;

public class ScreenshotEmailTest {
    public static WebDriver driver;

    public static void main(String[] arg) throws IOException, MessagingException {

        // set system property and initialize the chrome driver
        System.setProperty("webdriver.chrome.driver", "/home/dhawal/Downloads/chromedriver/chromedriver");
        driver = new ChromeDriver();
        SendEmail email = new SendEmail();
        
        driver.manage().window().maximize();
        driver.get("https://www.facebook.com/");

        
        // Take screenshot on step failure

        try {

            driver.findElement(By.name("email")).sendKeys("Screenshot on failure");
            driver.findElement(By.name("pass")).sendKeys("password");

            // Input wrong locator value for Log In button
            driver.findElement(By.xpath("//input[@type='submit_error']")).click();
        } catch (Throwable e) {
            
            //Write code to take screenshot and save it
            File file_error = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            FileHandler.copy(file_error, new File("/home/dhawal/scr_error.png"));
            
            //call the email reference
            email.postMail(SendEmail.emailList, SendEmail.emailSubjectTxt, SendEmail.emailMsgTxt, SendEmail.emailFromAddress);
            
        }
       
    }
    


}

Take Screenshot Of Failed Test Cases Using Selenium

Click HERE

If you run above class, it should fail as the Log In locator is incorrect. It should also create a png file scr_error in the specified directory. The code (which is prone to fail) is written under try block. catch block would contain the logic to take the screenshot and send an email:

 

Email Result On Test Step Failure
Execution Result of ScreenshotEmailTest.java

Screenshot of the failed test step captured at run time:

 

Script Failed After Entering Email and Password – scr_error.png

Below is the screenshot of the received email upon test step failure:

 

Email Of Failed Test Step

Login to your google account and turn on access for less secure apps under Security tab.

Click Here to visit Security Tab.

You may save SendEmail.java class for future use, as it is a reusable class. Try to modify the code to send the screenshot file as an attachment. 

Let me know in the comments if you face any difficulty in sending the email with the attachment.

Author: Dhawal Joshi

A post-graduate in MCA, ISTQB & ITIL certified QA with more than 8 years of experience in QA working with a CMMI Level 5 organization as System Analyst. I started my automation journey with HP UFT(formerly known as QTP) and for the past few years, I am using Selenium for automation. I also have experience in Android Application Development, Java, HTML, and VBScript. When I am not working, I like to spend time with my family, cooking and learning new developments in IT.

6 thoughts on “Send Email For Failed Step In Selenium

  1. Could not connect to SMTP host: smtp.gmail.com, port: 25;
    nested exception is:
    java.net.SocketException: Permission denied: connect

    I am getting above error

  2. Hi Dhawal: Very good tutorial.

    Could you please help me? I want to send the screenshot file as an attachment, but I cannot reach to do that.

  3. Great article ,
    Im trying to find solution for attaching screenshots to an email ,
    Under every script I would like to attach screenshot , Im using Jenkins , selenium is it possible ?
    Report email example :

    script status screenshot
    login to page Failed (Attach screenshot here)

  4. Hi,
    I am having trouble in below code, getting errors:
    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);
    session.setDebug(debug);
    Please help here. Thanks!

Leave a Reply

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