Automatically Email the reports after Selenium test execution

How to automatically trigger email with reports after execution ?

There might be situations, where you might be tasked by the management people or your clients to send email after your every test execution. Here is a solution for that

This post exclusively written as requested by one of our fellow readers of this blog 🙂

In this post we are going to look how we can send email to the clients
or stakeholders after the selenium test execution has been completed.

The program which we need include in Selenium Framework is,
Download here the Mail.jar
Download here the activation.jar


//The jar files which I have used are activation.jar and mail.jar Can be downloaded from Internet.

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendMail

{
//reportFileName = TestExecutionResultFileName
public static void execute(String reportFileName) throws Exception

{
String path=<Report file path>;

String[] to={"<stakeholder1>","<stakeholder2>"};
String[] cc={};
String[] bcc={"<AutomationTester>"};

SendMail.sendMail("<AutomationTesterUserName>",
"<AutomationTesterPassword>",
"smtp.gmail.com",
"465",
"true",
"true",
true,
"javax.net.ssl.SSLSocketFactory",
"false",
to,
cc,
bcc,
"<Subject line>",
"<Contents if any>",
path,
reportFileName);
}

public static boolean sendMail(String userName,
String passWord,
String host,
String port,
String starttls,
String auth,
boolean debug,
String socketFactoryClass,
String fallback,
String[] to,
String[] cc,
String[] bcc,
String subject,
String text,
String attachmentPath,
String attachmentName){

//Object Instantiation of a properties file.
Properties props = new Properties();

props.put("mail.smtp.user", userName);

props.put("mail.smtp.host", host);

if(!"".equals(port)){
props.put("mail.smtp.port", port);
}

if(!"".equals(starttls)){
props.put("mail.smtp.starttls.enable",starttls);
props.put("mail.smtp.auth", auth);
}

if(debug){

props.put("mail.smtp.debug", "true");

}else{

props.put("mail.smtp.debug", "false");

}

if(!"".equals(port)){
props.put("mail.smtp.socketFactory.port", port);
}
if(!"".equals(socketFactoryClass)){
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
}
if(!"".equals(fallback)){
props.put("mail.smtp.socketFactory.fallback", fallback);
}

try{

Session session = Session.getDefaultInstance(props, null);

session.setDebug(debug);

MimeMessage msg = new MimeMessage(session);

msg.setText(text);

msg.setSubject(subject);

Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentPath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachmentName);
multipart.addBodyPart(messageBodyPart);

msg.setContent(multipart);
msg.setFrom(new InternetAddress(userName));

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

for(int i=0;i<cc.length;i++){
msg.addRecipient(Message.RecipientType.CC, new
InternetAddress(cc[i]));
}

for(int i=0;i<bcc.length;i++){
msg.addRecipient(Message.RecipientType.BCC, new
InternetAddress(bcc[i]));
}

msg.saveChanges();

Transport transport = session.getTransport("smtp");

transport.connect(host, userName, passWord);

transport.sendMessage(msg, msg.getAllRecipients());

transport.close();

return true;

} catch (Exception mex){
mex.printStackTrace();
return false;
}
}
}

The above Source code will do the job of triggering email after every execution.


Where to how to use it?


Add the below snippet at the end of the test execution report creation.
[sourcecode language=”java”]
SendMail.execute(ExecutionFileName);[/sourcecode]

With this the whole setup of automatic email triggering functionality is integrated with our framework.

31 thoughts on “Automatically Email the reports after Selenium test execution

  1. Hi
    In the above code for this “String path=” What we need to give the “Report File path”
    And In this command “SendMail.execute(Execution File Name)” What we need to give the “Execution File Name”

    Please clarify above 2 things ,this would helpful to understand .

    Regards,
    Satish.M

    • String path = (Just mention the path where your reports are generated at your local machine. eg: C:/seleniumworkspace/reports)

      SendMail.execute(Just specify the file name of the report created for the corresponding test execution)
      for eg. consider a report is generated for a test execution. This report will be located in C:/seleniumworkspace/reports/testcase1.html)
      In this case, the method we need to mention will be : SendMail.execute(testcase1.html)

  2. Hi Manoj,

    Nice Blog.I am trying to send report from gmail id to yahoo id by using above code. Subject and attachments are coming in yahoomail id. But message text is not coming.My testscript has run successfully.Please look at this issue.Thanks in advance..

  3. Hi Manoj,

    Nice Blog.I am trying to send report from gmail id to yahoo id by using above code. Subject and attachments are coming in yahoomail id. But message text is not coming.My testscript has run successfully.Please look at this issue.Thanks in advance

  4. Can you explain this code once,that’ll be very helpful..

    SendMail.sendMail(“”,
    “”,
    “smtp.gmail.com”,
    “465”,
    “true”,
    “true”,
    true,
    “javax.net.ssl.SSLSocketFactory”,
    “false”,
    to,
    cc,
    bcc,
    “”,
    “”,
    path,
    reportFileName);
    }

  5. This code is working fine for me. But every time I execute my tests, it publishes the previous report via Email not the latest one.
    Any solution for that ?
    I am calling SendMail function in my teardown.

  6. I am getting Below Exception
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at sendMail.SendMail4.execute(SendMail4.java:70)
    at sendMail.sel.main(sel.java:10)

  7. I want to send the email only when the test execution fails.
    @AfterSuite(dependsOnMethods = { “CustomListener.onTestFailure” })

    This doesn’t works. Any thoughts!
    🙂

    • I think html report will complete its generation after AfterSuite function is implemented. if you call sendmail from after suite, probably html report would not have completed generating complete report hence does not work. Let After Suite finish executing and call sendmail separately. This could work for you.

  8. Where to add below code if I am using .xml file to generate execution report? Please help

    [sourcecode language=”java”]
    SendMail.execute(ExecutionFileName);[/sourcecode]

  9. can I have any idea, how to integrate with Jenkins cucumber report? I have location of the path where report generates and store, how can I configure to call this method.
    Thanks,
    Amar

  10. How can I trigger mail through webmail? getting below exception,

    java.net.UnknownHostException:

    Thanks in Advance

  11. I’m getting error as below. Can you please provide a solution.

    DATA
    354 Enter message, end with “.” on a line by itself
    java.io.FileNotFoundException: C:\data\test (Access is denied)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.(FileInputStream.java:138)
    at javax.activation.FileDataSource.getInputStream(FileDataSource.java:97)
    at javax.activation.DataHandler.writeTo(DataHandler.java:305)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1147)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:668)
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:233)
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:67)
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:889)
    at javax.activation.DataHandler.writeTo(DataHandler.java:317)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1147)
    at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1607)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:390)
    at com.connect.qc.SendMail.sendMail(SendMail.java:107)
    at com.connect.qc.SendMail.main(SendMail.java:21)

    Mine is a Non SSL port, for which I passed blank “” instead of “javax.net.ssl.SSLSocketFactory” and “starttls” as “false”.

    Any help would be highly appreciated.

  12. Hi

    Have you got any solution for sending an automatic email once all test scenarios are executed using Java Cucumber. I found no one has implemented emailing the report automatically once all scenarios has been executed.

    Please share if you have any solutions for this

    • @Anand,

      I have custom HTML reports generated after my execution in Java cucumber.
      and I am making a call to send the email with the help of @AfterClass in my Testclass.

      If this is something you want to try, i can help you with that…

  13. Hello , THanks for your help, but every time i am getting when in run my java code , do you have any idea about this :
    DEBUG: setDebug: JavaMail version 1.3.1
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465

    220 smtp.gmail.com ESMTP 81sm36275021pfm.90 – gsmtp
    DEBUG SMTP: connected to host “smtp.gmail.com”, port: 465

    EHLO VVK
    250-smtp.gmail.com at your service, [196.207.119.97]
    250-SIZE 35882577
    250-8BITMIME
    250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
    250-ENHANCEDSTATUSCODES
    250-PIPELINING
    250-CHUNKING
    250 SMTPUTF8
    DEBUG SMTP: Found extension “SIZE”, arg “35882577”
    DEBUG SMTP: Found extension “8BITMIME”, arg “”
    DEBUG SMTP: Found extension “AUTH”, arg “LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH”
    DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
    DEBUG SMTP: Found extension “PIPELINING”, arg “”
    DEBUG SMTP: Found extension “CHUNKING”, arg “”
    DEBUG SMTP: Found extension “SMTPUTF8”, arg “”
    DEBUG SMTP: Attempt to authenticate
    AUTH LOGIN
    334 VXNlcm5hbWU6
    dGVzdHFhZGVsaGkxMjI=
    334 UGFzc3dvcmQ6
    dml2ZWtAMTIzNA==
    235 2.7.0 Accepted
    DEBUG SMTP: use8bit false
    MAIL FROM:
    250 2.1.0 OK 81sm36275021pfm.90 – gsmtp
    RCPT TO:
    250 2.1.5 OK 81sm36275021pfm.90 – gsmtp
    DEBUG SMTP: Verified Addresses
    DEBUG SMTP: vivek876@gmail.com
    DATA
    354 Go ahead 81sm36275021pfm.90 – gsmtp
    java.io.FileNotFoundException: .\test-output (Access is denied)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.(Unknown Source)
    at javax.activation.FileDataSource.getInputStream(Unknown Source)
    at javax.activation.DataHandler.writeTo(Unknown Source)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1147)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:668)
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:233)
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:67)
    at javax.activation.ObjectDataContentHandler.writeTo(Unknown Source)
    at javax.activation.DataHandler.writeTo(Unknown Source)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1147)
    at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1607)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:390)
    at testclasses.SendMail.sendMail(SendMail.java:146)
    at testclasses.SendMail.execute(SendMail.java:32)
    at testclasses.NewTest.aftertest(NewTest.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
    at org.testng.TestRunner.afterRun(TestRunner.java:1027)
    at org.testng.TestRunner.run(TestRunner.java:627)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
    at org.testng.SuiteRunner.run(SuiteRunner.java:259)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1185)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1110)
    at org.testng.TestNG.run(TestNG.java:1018)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
    javax.mail.MessagingException: IOException while sending message;
    nested exception is:
    java.io.FileNotFoundException: .\test-output (Access is denied)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:421)
    at testclasses.SendMail.sendMail(SendMail.java:146)
    at testclasses.SendMail.execute(SendMail.java:32)
    at testclasses.NewTest.aftertest(NewTest.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
    at org.testng.TestRunner.afterRun(TestRunner.java:1027)
    at org.testng.TestRunner.run(TestRunner.java:627)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
    at org.testng.SuiteRunner.run(SuiteRunner.java:259)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1185)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1110)
    at org.testng.TestNG.run(TestNG.java:1018)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
    PASSED: functiontest

Leave a Comment