Bug 38029 - Using mail logger with large builds (code attached)
Summary: Using mail logger with large builds (code attached)
Alias: None
Product: Ant
Classification: Unclassified
Component: Core (show other bugs)
Version: 1.6.5
Hardware: All All
: P2 enhancement with 1 vote (vote)
Target Milestone: 1.8.0
Assignee: Ant Notifications List
Keywords: PatchAvailable
Depends on:
Reported: 2005-12-23 15:15 UTC by omri spector
Modified: 2008-10-14 08:16 UTC (History)
2 users (show)

diff -u of patch to mail logger (5.88 KB, patch)
2005-12-24 17:55 UTC, omri spector
Details | Diff

Note You need to log in before you can comment on or make changes to this bug.
Description omri spector 2005-12-23 15:15:04 UTC
I perform nightly builds for a fairly large system. I use mail logger 
for both success and notification since I want to be sure build ran and 
handle any problems asap.
I found that mail logger's notification, which contains the full build 
log, is problematic - it encumbers my e-mail.

In my site I improved on this by changing 
org.apache.tools.ant.listener.MailLogger to support an additional 
attribute, MailLogger.body, which sends a fixed body.
I then run the build with a fixed body ("Build log can be found at....") and a 
logfile to a central directory (i.e.
ant build.nightly -logfile log\build.log -logger 
org.apache.tools.ant.listener.MailLogger -

With properties:

MailLogger.body=Nightly build log can be found at \\\\win-build-1

This works nicely for me, and I think is a nice feature. 

I attach the code:
 * Copyright  2002-2004 The Apache Software Foundation
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
package org.apache.tools.ant.listener;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Properties;
import java.util.Enumeration;
import java.util.StringTokenizer;

import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.email.EmailAddress;
import org.apache.tools.ant.taskdefs.email.Message;
import org.apache.tools.ant.taskdefs.email.Mailer;
import org.apache.tools.ant.util.DateUtils;
import org.apache.tools.ant.util.StringUtils;
import org.apache.tools.mail.MailMessage;

 *  Buffers log messages from DefaultLogger, and sends an e-mail with the
 *  results. The following Project properties are used to send the mail.
 *  <ul>
 *    <li> MailLogger.mailhost [default: localhost] - Mail server to use</li>
 *    <li> MailLogger.port [default: 25] - Default port for SMTP </li>
 *    <li> MailLogger.from [required] - Mail "from" address</li>
 *    <li> MailLogger.failure.notify [default: true] - Send build failure
 *    e-mails?</li>
 *    <li> MailLogger.success.notify [default: true] - Send build success
 *    e-mails?</li>
 *    <li> MailLogger.failure.to [required if failure mail to be sent] - 
 *    to send failure messages to</li>
 *    <li> MailLogger.success.to [required if success mail to be sent] - 
 *    to send success messages to</li>
 *    <li> MailLogger.failure.subject [default: "Build Failure"] - Subject of
 *    failed build</li>
 *    <li> MailLogger.success.subject [default: "Build Success"] - Subject of
 *    successful build</li>
 *    <li> MailLogger.body [default: ""] - Body of sent mail. If omitted, 
 *    log will be sent. Useful in conjunction with -logfile for very long 
 *  </ul>
 *  These properties are set using standard Ant property setting mechanisms
 *  (&lt;property&gt;, command-line -D, etc). Ant properties can be overridden
 *  by specifying the filename of a properties file in the <i>
 *  MailLogger.properties.file property</i> . Any properties defined in that
 *  file will override Ant properties.
public class MailLogger extends DefaultLogger {
    /** Buffer in which the message is constructed prior to sending */
    private StringBuffer buffer = new StringBuffer();
    /** Properties used when configuring loader **/
    Hashtable properties;

     *  Sends an e-mail with the log results.
     * @param event the build finished event
    public void buildFinished(BuildEvent event) {
        boolean success = (event.getException() == null);
        String prefix = success ? "success" : "failure";

        try {
        	String fixedBody=getValue("body","");
            boolean notify = Project.toBoolean(getValue(prefix 
+ ".notify", "on"));

            if (!notify) {

            String mailhost = getValue("mailhost", "localhost");
            int port = Integer.parseInt(getValue("port",
            String user = getValue("user", "");
            String password = getValue("password", "");
            boolean ssl = Project.toBoolean(getValue(
                     "ssl", "off"));
            String from = getValue("from", null);
            String replytoList = getValue("replyto", "");
            String toList = getValue(prefix + ".to", null);
            String subject = getValue(prefix + ".subject",
                    (success) ? "Build Success" : "Build Failure");
            String body=(fixedBody.length()==0? buffer.substring(0) : 
            if (user.equals("") && password.equals("") && !ssl) {
                sendMail(mailhost, port,  from, replytoList, toList,
                         subject, body);
            } else {
                sendMimeMail(event.getProject(), mailhost, port, user,
                             password, ssl, from, replytoList, toList,
                             subject, body);
        } catch (Exception e) {
            System.out.println("MailLogger failed to send e-mail!");

    private void loadProperties(Project  project){
        properties = project.getProperties();

        // overlay specified properties file (if any), which overrides project
        // settings
        Properties fileProperties = new Properties();
        String filename = (String) properties.get
        if (filename != null) {
            InputStream is = null;
            try {
                is = new FileInputStream(filename);
            } catch (IOException ioe) {
                // ignore because properties file is not required
            } finally {
                if (is != null) {
                    try {
                    } catch (IOException e) {
                        // ignore

        for (Enumeration e = fileProperties.keys(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            String value = fileProperties.getProperty(key);
            properties.put(key, project.replaceProperties(value));

     *  Receives and buffers log messages.
     * @param message the message being logger
    protected void log(String message) {
    	// it would have been nice to avoid this in "fixed body" mode, but 
    	// I could not get properties at buildStart event.

     *  Gets the value of a property.
     * @param  properties     Properties to obtain value from
     * @param  name           suffix of property name. "MailLogger." will be
     *      prepended internally.
     * @param  defaultValue   value returned if not present in the properties.
     *      Set to null to make required.
     * @return                The value of the property, or default value.
     * @exception  Exception  thrown if no default value is specified and the
     *      property is not present in properties.
    private String getValue(String name,
                            String defaultValue) throws Exception {
        String propertyName = "MailLogger." + name;
        String value = (String) properties.get(propertyName);

        if (value == null) {
            value = defaultValue;

        if (value == null) {
            throw new Exception("Missing required parameter: " + propertyName);

        return value;

     *  Send the mail
     * @param  mailhost         mail server
     * @param  port             mail server port number
     * @param  from             from address
     * @param  replyToList      comma-separated replyto list
     * @param  toList           comma-separated recipient list
     * @param  subject          mail subject
     * @param  message          mail body
     * @exception  IOException  thrown if sending message fails
    private void sendMail(String mailhost, int port, String from, String 
replyToList, String toList,
                          String subject, String message) throws IOException {
        MailMessage mailMessage = new MailMessage(mailhost, port);
        mailMessage.setHeader("Date", DateUtils.getDateForHeader());

        if (!replyToList.equals("")) {
            StringTokenizer t = new StringTokenizer(replyToList, ", ", false);
            while (t.hasMoreTokens()) {
        StringTokenizer t = new StringTokenizer(toList, ", ", false);
        while (t.hasMoreTokens()) {


        PrintStream ps = mailMessage.getPrintStream();

     *  Send the mail  (MimeMail)
     * @param  project          current ant project
     * @param  host             mail server
     * @param  port             mail server port number
     * @param  user             user name for SMTP auth
     * @param  password         password for SMTP auth
     * @param  ssl              if true send message over SSL
     * @param  from             from address
     * @param  replyToString    comma-separated replyto list
     * @param  toString         comma-separated recipient list
     * @param  subject          mail subject
     * @param  message          mail body
    private void sendMimeMail(Project project, String host, int port,
                              String user, String password, boolean ssl,
                              String from, String replyToString,
                              String toString, String subject,
                              String message)  {
        // convert the replyTo string into a vector of emailaddresses
        Mailer mailer = null;
            try {
                mailer =
                    (Mailer) Class.forName
            } catch (Throwable e) {
                log("Failed to initialise MIME mail: " + e.getMessage());
        Vector replyToList = vectorizeEmailAddresses(replyToString);
        Message mymessage = new Message(message);
        mailer.setFrom(new EmailAddress(from));
        Vector toList = vectorizeEmailAddresses(toString);
        mailer.setCcList(new Vector());
        mailer.setBccList(new Vector());
        mailer.setFiles(new Vector());
    private Vector vectorizeEmailAddresses(String listString) {
        Vector emailList = new Vector();
        StringTokenizer tokens = new StringTokenizer(listString, ",");
        while (tokens.hasMoreTokens()) {
            emailList.addElement(new EmailAddress(tokens.nextToken()));
        return emailList;
Comment 1 Matt Benson 2005-12-23 16:04:21 UTC
code should be attached to the bugzilla report using the attachment facility. 
When such an attachment comprises modifications to existing Ant source it should
be presented as a unified diff (see

Comment 2 omri spector 2005-12-24 17:55:46 UTC
Created attachment 17274 [details]
diff -u of patch to mail logger

I am attaching a diff for the exact patch I performed
Comment 3 Stefan Bodewig 2008-10-14 08:16:35 UTC
implemented as two different properties for the success/failure cases with svn revision 704562.