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.
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
- Download java mail jar file which contains the library to send the email.
- Add jar into your project and if you are working with maven project then you can use dependency.
- Be ready with the file which you want to send. In our case, it will be Selenium Report.
- 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.
Deepti says
I am getting the error – [AppClassLoader@18b4aac2] warning javax.* types are not being woven because the weaver option ‘-Xset:weaveJavaxPackages=true’ has not been specified.
I am trying to attach the emailable report. Please help.
Mukesh Otwani says
Hi Deepti,what is your requirment? Now gmail does not allow password, you need to create app password then use the same while sending password. I have shown the same in my this video https://www.youtube.com/watch?v=TqiBFlU3ACU
VarunMehta says
I am getting “530 5.7.0 Must issue a STARTTLS command first. b15-20020a170902b60f00b001aafe232bcfsm1470623pls.44 – gsmtp”
Mukesh Otwani says
Recently some changes in gmail setting for sending emails, please check this video https://www.youtube.com/watch?v=TqiBFlU3ACU&pp=ygUraG93IHRvIHNlbmQgZW1haWwgaW4gamVua2lucyAgbXVrZXNoIG90d2FuaQ%3D%3D
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
Mukesh Otwani says
Hi Sharad, please use different versions to fix this issue.
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
Mukesh Otwani says
Hi Chaitanya,
Which report are you sending? Is it TestNG or ExtentReport?
Vinay says
Hi Mukesh,
I’m using cucumber along with appium need to send emailable report can i use the same code
Mukesh Otwani says
Hi Vinay,
This is independent java lib to send emails so you can use for any reports.
Thanks
Mukesh Otwani
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
Mukesh Otwani says
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
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
Mukesh Otwani says
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
pavithra says
Can u suggest any link that supports your response
Mukesh Otwani says
Hi Pavithra,
Please refer this link
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.
Mukesh Otwani says
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.
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?
Mukesh Otwani says
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.
sonam kumari says
Hello Mukesh,
Is it possible to download a file and send it through email using above code?
Waiting for your reply
Mukesh Otwani says
Hi Sonam,
Using Java Mail APIs, you can attach files too but it doesn’t support any file downloading.
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?
Mukesh Otwani says
Hi Destany,
Which report are you sending through email?
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.
Mukesh Otwani says
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
Rajasekhar says
Hi Mukesh, Could you please help on how to send the link of extent report
Mukesh Otwani says
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
Divakar says
hi Vipin, can you help me by sharing some reference link to configure Extent report and send it over email please…
Mukesh Otwani says
Hi Divakar,
Please refer this link https://www.youtube.com/watch?v=WdenIgyGDyw
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.
Mukesh Otwani says
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.
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
Mukesh Otwani says
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
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
Mukesh Otwani says
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
ashok says
Thank you Mukesh
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.
Mukesh Otwani says
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
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.
Mukesh Otwani says
Hi Gagan,
Are you trying this from your office network/on some vpn?
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.
Mukesh Otwani says
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.
Vijaya says
Got it. Thank you.
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.
Mukesh Otwani says
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.
Arun says
when i am calling sendmail function in aftersuit the report is not getting updated at all
Mukesh Otwani says
Hi Arun,
May I know which report are you sending through email, is it TestNG Emailable-report?
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.
Mukesh Otwani says
Hi Mily,
In this situation, I recommend you to contact network/system admin because message itself showing authentication failure.
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)
Mukesh Otwani says
Hi Rodrigo,
I hope that you have added Java Mail API properly to your project build path…
Goutam says
Hi Mukesh,
Even I also getting same exception.
I added the dependency in maven.
Mukesh Otwani says
Hi Goutam,
Do you have any firewall restrictions in your network?
NKM says
To resolve this error use following in your pom.xml file:
com.sun.mail
javax.mail
1.6.0
Sushmitha says
HI mukesh ,
what are the port and host for outlook
Mukesh Otwani says
Hi Sushmitha,
Please check this link https://support.office.com/en-us/article/pop-imap-and-smtp-settings-for-outlook-com-d088b986-291d-42b8-9564-9c414e2aa040
pooja pilkhwal says
hi mukesh,
how can handle dynamic id through xpath in selenium web driver
Mukesh Otwani says
Hi Pooja,
Kindly refer below post http://learn-automation.com/how-to-write-dynamic-xpath-in-selenium/
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.
Mukesh Otwani says
HI Rathish,
Kindly use extent report (advance XSLT report) http://learn-automation.com/advance-selenium-reporting-with-screenshots-2/
Duc says
Hi Muhesk,
With yahoo mail, do we have to change which parameters? Please let me know. Thanks so much
Mukesh Otwani says
Yes Duc for yahoo smtp server details and port number has to be changed.
Priyaranjan says
Great help. Thanks for the wonderful post.
Is there any video, which we can refer, unlike your other sessions.
Mukesh Otwani says
In the process will post soon.
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!!
Mukesh Otwani says
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 🙂