Answer
Sending Email in Selenium Using javax.mail
Selenium does not have a built-in email feature, but Java's javax.mail (Jakarta Mail) library lets you send emails programmatically — typically called after test execution to notify stakeholders of pass/fail results.
Steps to Set Up
1. Add Maven dependency:
XML
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
2. Write the email utility:
Java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class EmailUtility {
public static void sendEmail(String subject, String body) throws Exception {
String host = "smtp.gmail.com";
String from = "your-email@gmail.com";
String password = "your-app-password";
String to = "stakeholder@company.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
System.out.println("Email sent successfully!");
}
}
3. Call after test execution (e.g., in TestNG @AfterSuite):
Java
@AfterSuite
public void sendReport() throws Exception {
EmailUtility.sendEmail(
"Test Execution Report - " + new Date(),
"Total: 50 | Passed: 45 | Failed: 5 | Skipped: 0"
);
}
Best Practices
- ✓Use Gmail App Passwords (not your real password) with 2FA enabled
- ✓Attach the ExtentReport HTML file using
MimeBodyPartfor detailed reports - ✓Send to a distribution list rather than individual addresses
- ✓Integrate with Jenkins to auto-email on build completion
