How to send a report through email using Selenium Webdriver?
Last Updated :
21 Aug, 2024
In the world of automation testing, generating and sharing test reports is crucial. After executing tests using Selenium WebDriver, it's often necessary to share the results with team members or stakeholders. Automating the process of sending these reports via email can save time and ensure that everyone stays informed about the testing outcomes.
In this article, we'll explore how to send a report through email using Selenium WebDriver, breaking down the steps and providing a complete program for easy implementation.
Sending Report Through Email in Selenium WebDriver
1. Set Up Your Environment
Before you start, make sure you have the necessary dependencies in your project. You'll need Selenium WebDriver for your test automation and JavaMail API to handle email sending. You can include these in your Maven project using the following dependencies:
XML
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.8.0</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
2. Create the Test Report
Execute your Selenium tests and generate the test report. You can use tools like TestNG or JUnit to create reports. These reports are typically in HTML or XML format. Ensure the report is saved in a known location as you'll need to attach it to your email.
3. Set Up JavaMail API
The JavaMail API allows you to send emails programmatically. You'll need to configure the SMTP server settings (like Gmail, Yahoo, etc.) to send emails. Here’s a simple setup using Gmail:
Java
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
4. Authenticate the Email Account
You'll need to authenticate the email account you're using to send the report. This is done using the Session object in JavaMail API:
Note: This is not the password by which you login to gmail, instead you need to generate an app password from your Google Account's Security settings. Link.
Make sure you used the right path of report file.
Java
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "your_password");
}
});
5. Compose the Email
Now, you can compose the email by setting the subject, recipients, and body. You can also attach your test report to the email:
Java
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Automated Test Report");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Please find the attached test report.");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Attach the report
messageBodyPart = new MimeBodyPart();
String filename = "path_to_report/report.html";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
6. Run the Program
After setting up the email-sending code, integrate it with your test automation framework. You can call this email-sending function at the end of your test execution to automatically send the report.
Complete Program to Send Reports Through Email in Selenium WebDriver
Here's a complete example program that ties everything together:
Java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmailWithReport {
public static void main(String[] args) {
// Set up the SMTP server settings
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Authenticate the email account
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "your_password");
}
});
try {
// Compose the email
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Automated Test Report");
// Email body text
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Please find the attached test report.");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Attach the report
messageBodyPart = new MimeBodyPart();
String filename = "path_to_report/report.html";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Combine message parts
message.setContent(multipart);
// Send the email
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Output:
Email sent successfully.
Conclusion
Sending test reports through email is an essential part of the automation testing process. By following the steps outlined in this article, you can seamlessly integrate email reporting into your Selenium WebDriver projects. This automated process not only saves time but also ensures that your team stays up-to-date with the latest test results.
Whether you're using Gmail or another email service, the JavaMail API offers a flexible and reliable way to send reports programmatically.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read