Advance Reporting

How to Send report through email in Selenium Webdriver

Send report through email in Selenium Webdriver

Do you know that we can send reports through email in Selenium Webdriver with small code with help of additional jars?

Today I will show you how you can send reports through email in Selenium Webdriver using simple steps and trust me this is one of the most important features that you should include in your framework as well.

It does not matter which framework you are using it could be Keyword driver, Data-driven, and Hybrid you should implement email report functionality after test execution.

 

Send report through email in Selenium Webdriver

 

Options to send email in Java

1- Apache Common Email– This is a very easy library in Java, which can help you to send an email with few lines of code.

You can use simple email and email with attachments as well.

                                          I have a dedicated video on this that covers the same.

2- Java mail jar  – Another lib to send email in Java. 

 

Step by Step process to Send report through email in Selenium Webdriver

  1. Download java mail jar file which contains the library to send the email.
  2. download-jar-for-email
  3. Add jar into your project and if you are working with maven project then you can use dependency.
  4. Be ready with the file which you want to send. In our case, it will be Selenium Report.
  5. Write program, which will send the email to the team or a specific person.

 

Complete program to Send report through email in Selenium Webdriver

 

package macSelenium;

import java.util.Properties;

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.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 SendMailSSLWithAttachment {

	public static void main(String[] args) {

		// Create object of Property file
		Properties props = new Properties();

		// this will set host of server- you can change based on your requirement 
		props.put("mail.smtp.host", "smtp.gmail.com");

		// set the port of socket factory 
		props.put("mail.smtp.socketFactory.port", "465");

		// set socket factory
		props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");

		// set the authentication to true
		props.put("mail.smtp.auth", "true");

		// set the port of SMTP server
		props.put("mail.smtp.port", "465");

		// This will handle the complete authentication
		Session session = Session.getDefaultInstance(props,

				new javax.mail.Authenticator() {

					protected PasswordAuthentication getPasswordAuthentication() {

					return new PasswordAuthentication("add your email", "add your password");

					}

				});

		try {

			// Create object of MimeMessage class
			Message message = new MimeMessage(session);

			// Set the from address
			message.setFrom(new InternetAddress("mukeshotwani.50@gmail.com"));

			// Set the recipient address
			message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("mukesh.otwani50@gmail.com"));
            
                        // Add the subject link
			message.setSubject("Testing Subject");

			// Create object to add multimedia type content
			BodyPart messageBodyPart1 = new MimeBodyPart();

			// Set the body of email
			messageBodyPart1.setText("This is message body");

			// Create another object to add another content
			MimeBodyPart messageBodyPart2 = new MimeBodyPart();

			// Mention the file which you want to send
			String filename = "G:\\a.xlsx";

			// Create data source and pass the filename
			DataSource source = new FileDataSource(filename);

			// set the handler
			messageBodyPart2.setDataHandler(new DataHandler(source));

			// set the file
			messageBodyPart2.setFileName(filename);

			// Create object of MimeMultipart class
			Multipart multipart = new MimeMultipart();

			// add body part 1
			multipart.addBodyPart(messageBodyPart2);

			// add body part 2
			multipart.addBodyPart(messageBodyPart1);

			// set the content
			message.setContent(multipart);

			// finally send the email
			Transport.send(message);

			System.out.println("=====Email Sent=====");

		} catch (MessagingException e) {

			throw new RuntimeException(e);

		}

	}

}

 

Above program will send the report to the respective recipient with the attachment. 

You can also send  the email via Jenkins which is quite easy but you are not using Jenkins then you can use above program.

 

Important points

1- You can create a custom library which should accept recipients as arguments so that we can reuse this as much we can.

2- Write the logic to get the path of the report, so that we can set the same in our methods.

3- Always call this code after test execution. You can use @AfterSuite of TestNG which run only when complete suite execute.

 

Conclusion

1- Sending reports after every execution is very important but if you are running multiple tests in one day better to send combined reports at once.

2-Try to keep all screenshots in a common location where everyone will have access so when they click on report and screenshot then it should be accessible.

I hope you liked the above article on Send report through email in Selenium Webdriver.

Please try from your side as well and let me know if any thoughts on this.

Sharing knowledge can seem like a burden to some
but on the contrary,
it is a reflection of teamwork and leadership.

So kindly share with your friends and team member.

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

65 thoughts on “How to Send report through email in Selenium Webdriver

  1. VarunMehta says:

    I am getting “530 5.7.0 Must issue a STARTTLS command first. b15-20020a170902b60f00b001aafe232bcfsm1470623pls.44 – gsmtp”

  2. Sharad Gupta says:

    Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
    at javax.mail.Session.initLogger(Session.java:283)
    at javax.mail.Session.(Session.java:268)
    at javax.mail.Session.getDefaultInstance(Session.java:378)
    at utilities.SendMailSSLWithAttachment.main(SendMailSSLWithAttachment.java:45)
    Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    … 4 more

    1. Hi Sharad, please use different versions to fix this issue.

  3. Chaitanya says:

    Hi Mukesh,

    I’m able to sent report in Email, but after downloading the report, its displaying as empty.
    Any suggestions how to rectify it

    1. Hi Chaitanya,

      Which report are you sending? Is it TestNG or ExtentReport?

  4. Vinay says:

    Hi Mukesh,

    I’m using cucumber along with appium need to send emailable report can i use the same code

    1. Hi Vinay,
      This is independent java lib to send emails so you can use for any reports.

      Thanks
      Mukesh Otwani

  5. Kulvir singh says:

    hello sir
    my test case is not showing in extent report as there sequence
    it showing test result in chronological manner but i want to show in as per there execution order
    plsese help me or suggest any your video
    i m use selenium 2.53.0
    extent:-2.41.2
    testNG:-6.8.5

    1. Hi Kulvir,

      Please refer this https://www.extentreports.com/docs/versions/2/java/index.html#initialize-report
      Look for displayOrder
      OLDEST_FIRST (default) – oldest test at the top, newest at the end
      NEWEST_FIRST – newest test at the top, oldest at the end

  6. pavithra says:

    Hi sir i have a project where 10 test cases are there. i need to send all testcases result in single mail with report.
    how can i do this

    1. Hi Pavithra,

      You need to have all tests/test classes under one suite. Report initialization and sending email should happen at the Suite level. This can be achieved easily with the TestNG framework. If you are using Extent Report, then ExtentTest object should be initialized at test level. Report closure under @AfterSuite follows Email Sending

      1. pavithra says:

        Can u suggest any link that supports your response

        1. Hi Pavithra,

          Please refer this link

  7. Rahul Gabani says:

    Hello Mukesh,

    Can you help me to know how can we show the summary of result in email body and detailed report as an attachment to email. I also want to add few words in email body as well. I am planning to send an email through outlook company email.

    1. Hey Rahul,
      This video might help https://www.youtube.com/watch?v=qGq9K85mGyA
      Outlook is just software so you can configure with gmail, yahoo or any other email. In order to send email just get smtp and other details from IT and you can use the same.

  8. Gaurav Vats says:

    Hi i want to send report through my outlook account and email address is in my company domain i dont know its smtp server and port details do i need to ask someone for this?

    1. Hi Gaurav,

      Ideal way to send email notification is using code/script because when you will run your test in CI/CD then outlook wont be configured. If you still want to send email using Outlook then use WinAppDriver or Winium or RPA tools.
      Note-You can get your email server details from IT team/support.

  9. sonam kumari says:

    Hello Mukesh,

    Is it possible to download a file and send it through email using above code?

    Waiting for your reply

    1. Hi Sonam,

      Using Java Mail APIs, you can attach files too but it doesn’t support any file downloading.

  10. Destany says:

    My report is sending correct, but when I open up the report it seems to be missing the CSS styles. SO my report looks like plain text and its hard to read. Any Idea on how I could fix this issue?

    1. Hi Destany,

      Which report are you sending through email?

      1. vipin says:

        i am also facing the same issue.I am using extent report. version 4.1.1.After sending the report to gmail its css styles are not working.please help me for this issue,I really need your support.

        1. Hi Vipin,

          If you send an Extent report Html file as an attachment to anywhere outside the system from where it has been generated then the report will definitely lose its many javascript and CSS. These supporting files remain in the origin system. Extent report is a feature-rich report not like a simple TestNG html report. It is always recommendable to send the link of the report to anybody you want

          1. Rajasekhar says:

            Hi Mukesh, Could you please help on how to send the link of extent report

          2. Hi Rajasekhar,
            You can either use Java Mail APIs to email from your script or from any build tool which executes your scripts remotely like Jenkins, Bamboo. Fir st you need to identify the path of report then use that link in email body

        2. Divakar says:

          hi Vipin, can you help me by sharing some reference link to configure Extent report and send it over email please…

  11. Nidhi says:

    Hi Mukesh,

    I am using default TestNG Emailable-report to generate the report.
    Facing an issue with report when i run sendmail function, email is sent successfully.
    but email contains old report instead of new one.

    Please help me to solve this issue.

    1. Hi Nidhi,

      This is known issue with TestNg library. But there is a alternate way, if you are maven project along with surefire-plugin is already residing inside project then you will be same report getting generated under target-> surefire-report folder. This will always generate new report.

      1. nagamani says:

        i did but i didn’t even get lat latest report…i put surefire plugin in pom.xml..i am running code but i didn’t even get any folder in target

        1. Hi Nagamani,

          In order to get target folder, you need to run your script through the maven command. Please visit this link https://www.youtube.com/watch?v=WIiFTb9RMNw

  12. Ashok says:

    Hi Mukesh,

    Mail functionality is properly working but I am getting previous report.
    Please help me to solve this issue.

    Awaiting for your reply

    1. Hi Ashok,

      If you are talking about testng emailable-report then I would suggest you to take same report from target -> surefire-reports. This will come when you have surefire plugin installed in your project through pom.xml

      1. ashok says:

        Thank you Mukesh

  13. Gagan Sehgal says:

    Hi sir,
    Trying to send email using code but every time it is showing error.

    Exception in thread “main” org.apache.commons.mail.EmailException: Sending the email to the following server failed : mail.gmail.com:465
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1398)
    at org.apache.commons.mail.Email.send(Email.java:1423)
    at Email.SendEmailJava.sendEmail(SendEmailJava.java:27)
    at Email.SendEmailJava.main(SendEmailJava.java:12)
    Caused by: javax.mail.MessagingException: Unknown SMTP host: mail.gmail.com;
    nested exception is:
    java.net.UnknownHostException: mail.gmail.com
    i tried to execute it as per your explanation but not getting the solution of this error. Please help.

    1. Hi Gagan,

      Have you used below mentioned details
      SMTP server address: smtp.gmail.com
      SMTP username: Your Gmail address (for example, example@gmail.com)
      SMTP password: Your Gmail password
      SMTP port (TLS): 587
      SMTP port (SSL): 465
      SMTP TLS/SSL required: Yes

      Moreover, if you’re trying this inside your organization network then kindly check with your network admin that there is no proxy/firewall

      1. Gagan Sehgal says:

        Yes Sir i have used all of these details in my code.

        i tried to perform this as you showed in the video but it is showing the error which i have sent you above.

        1. Hi Gagan,

          Are you trying this from your office network/on some vpn?

  14. Vijaya says:

    Hi Mukesh,

    How to get all records from the UI Table if pagination exists? I am getting records from only the first page.
    Suppose the code for the table is
    col 1
    col 2
    td 1
    td 2

    and i have tried with the below code
    List allrecord= driver.findElements(By.xpath(“//*[@id=’demo-dt-basic’]/tbody/tr”));
    System.out.println(“The size of the records is “+allrecord.size());
    There are 199 entries in the table and 11 records display per page. I want to get all the records in the list. But I am getting size 11, That means only first page records are counting.

    1. Hi Vijaya,

      Once you get first 11 eleven items, save required values in an ArrayList and click on next page link. On new page, hopefully xpath won’t get change so you can use same xpath again to get next 11 items. Do this in looping mechanism till last page.

      1. Vijaya says:

        Got it. Thank you.

  15. Arun says:

    I have tried sending default TestNG Emailable-report and also the reportng index.html . The issue over here is if i run this sendmail function at the end in aftersuit . Though the executon completes successfully and mail is also sent. The report mailed is old one . The report is not updated at the end of execution at all.

    but if i comment the sendmail function then the report is successfully updated.

    1. Hi Arun,

      Apologies for late reply….
      As per @AfterSuite annotation, after execution of all statements inside corresponding method, TestNG report will get finalize as @AfterSuite annotated method is also part of your test execution. If you want to send emailable-report then you should use TestNg Listeners, which you can use after @AfterSuite annotated method.

  16. Arun says:

    when i am calling sendmail function in aftersuit the report is not getting updated at all

    1. Hi Arun,

      May I know which report are you sending through email, is it TestNG Emailable-report?

  17. Mily Chacko says:

    Hi Mukesh, Im getting an error as below:
    Caused by: javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful [SYBPR01CA0209.ausprd01.prod.outlook.co

    in-fact the program is for mailing m ethe reports post execution, and was working well. Its been a dy this error has started coming me without me changing any configurations. Kindly guide.

    1. Hi Mily,

      In this situation, I recommend you to contact network/system admin because message itself showing authentication failure.

  18. Rodrigo González says:

    Hi Mukesh. I’m facing the next error:

    Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
    at javax.mail.Session.initLogger(Session.java:261)
    at javax.mail.Session.(Session.java:245)
    at javax.mail.Session.getDefaultInstance(Session.java:356)
    at cl.cuadrante.util.email.EnviaMailConPantallazo.main(SendMailSSLWithAttachment.java:36)
    Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

    1. Hi Rodrigo,

      I hope that you have added Java Mail API properly to your project build path…

      1. Goutam says:

        Hi Mukesh,
        Even I also getting same exception.
        I added the dependency in maven.

        1. Hi Goutam,

          Do you have any firewall restrictions in your network?

        2. NKM says:

          To resolve this error use following in your pom.xml file:

          com.sun.mail
          javax.mail
          1.6.0

  19. Sushmitha says:

    HI mukesh ,

    what are the port and host for outlook

  20. pooja pilkhwal says:

    hi mukesh,
    how can handle dynamic id through xpath in selenium web driver

  21. Rathish says:

    Hi Mukesh,
    Thank you so much. Awesome Explanation. This article helped me a lot.

    I need one clarification. I was using XSLT report and generated index.html file. I have sent index.html file to my email id using the above program. When I open the file from my email. I am getting “Page cannot be displayed”. I am unable to view the report.

    Awaiting for your reply.

    Thanks in advance.

  22. Duc says:

    Hi Muhesk,
    With yahoo mail, do we have to change which parameters? Please let me know. Thanks so much

    1. Yes Duc for yahoo smtp server details and port number has to be changed.

  23. Priyaranjan says:

    Great help. Thanks for the wonderful post.

    Is there any video, which we can refer, unlike your other sessions.

    1. In the process will post soon.

  24. biswa busan mishra says:

    Hi Mukesh,

    Awesome explanation with much valuable information.
    I implemented the same in my frame works and successfully able to trigger the mail.
    But few clarification needed
    1.As of now am not using any xslt report or customised report ,am using the default testing one only.So each time need to refresh manually for generating the new mailable report.
    2.So After refresh its taking the updated file,else its triggering the old file only.
    3.So do we have any code for refreshing the local file automatically so that no need to do it manually.
    Awaiting for your reply!!
    Once again thanks a ton for the effort you spending.
    hats off to you mukesh!!

    1. Hi Biswa,

      Refresh task we have to do manually in eclipse but in local driver it refresh automatically. But still you can wait for sometime and the attach the report 🙂

Leave a Reply

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

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