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... -->
    </testng>
  </target>
 
  <!-- 
    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="your.mail.smtp.com" mailport="25" failonerror="false"
      subject="Your subject here...">
 
      <from address="from@company.com"/>
 
      <to address="to1@company.com"/>
      <to address="to2@company.com"/>
      <to address="to3@company.com"/>
      <to address="toX@company.com"/>
 
      <message>Your message here....</message>
 
      <attachments>
        <fileset dir=".">
          <include name="filename.txt"/>
        </fileset>
      </attachments>
 
    </mail>
  </target>
</project>  

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 OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.