Ant - Send email if tests failed

By xngo on June 29, 2019

Here is an example of how to set Ant build file to send out emails if tests failed.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="run_testng" name="SendEmailExample">
  <!-- Your TestNG target -->
  <target name="run_testng" >
    <testng failureProperty="test.failed">
      <!-- ... your TestNG instructions here... -->
    The target sendMail will be executed only if test.failed is true. 
      test.failed value come from <testng>, see run_testng target above. 
      Therefore, email will be sent only if the test failed. 
  <target name="sendMail" if="test.failed" depends="run_testng">
    <mail mailhost="" mailport="25" failonerror="false"
      subject="Your subject here...">
      <from address=""/>
      <to address=""/>
      <to address=""/>
      <to address=""/>
      <to address=""/>
      <message>Your message here....</message>
        <fileset dir=".">
          <include name="filename.txt"/>

If you are adding attachments to your email and you are getting the error message "Failed to initialise MIME mail: javax/mail/MessagingException", then download JavaMail API(i.e. mail.jar) and JavaBeans Activation Framework(i.e. activation.jar) and copy them in the lib/ folder of Ant.

About the author

Xuan Ngo is the founder of He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.