ant-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Tim O'Brien" <tmobr...@mindspring.com>
Subject RE: cvs commit:.... MailMessage.java
Date Wed, 19 Jul 2000 15:29:34 GMT
Tim,

	I wrote a javax.mail based Email task, that I use to do this on my own
instance, it isn't Ant standard in that it accepts multiple properties
inefficiently.  These things could be fixed, but I choose to drop the
subject because it was creating too much ant-dev traffic.  I was in the
middle of writing some code to use MailMessage.java, but the multiple
copyrights scared me off.  If you want to install the task on your own Ant
and fiddle with it...I've attached the task's code below.  You would use it
like this:

<email mailto="tmcginn@itemus.com,tobrien@ieee.org"
       message="Ant notification"
       subject="build"
       smtphost="mail.itemus.com"
       messagefile="fileContainsSomeText.txt"
       attachfile="billofrights.txt,theConstitution.txt">

Tim O'Brien
tobrien@ieee.org


Dusted off code for Email.java below ( Note this is not standard Ant in that
it accepts multiple inputs in strings. )

/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.tools.ant.taskdefs.optional;

import org.apache.tools.ant.*;
import java.io.*;
import java.net.*;
import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;

import javax.activation.*;

/**
 * Task to send email messages from Ant.  This task can take the following
 * arguments:
 * <ul>
 * <li><B>mailto</B> - A comma separated list of email addresses</li>
 * <li><B>mailfrom</B> - An email address from which mail is sent</li>
 * <li><B>subject</B> - The subject of the email message</li>
 * <li><B>message</B> - The message body</li>
 * <li><B>messagefile</B> - A comma separated list of files to include in
the message body</li>
 * <li><B>attachfile</B> - A comma separated list of files to attach as
MIME
attachments</li>
 * <li><B>smtphost</B> - SMTP host to send mail</LI>
 * </ul>
 * Of these arguments, <b>mailto</b> and <b>mailfrom</b> must be specified,
and one of the following
 * arguments must be present <B>message</B> and <B>messagefile</B>.
 *
 * @author Tim O'Brien <a
href="mailto:tobrien@ieee.org">tobrien@ieee.org</a>
 */
public class Email extends Task {

    private static final String delimiter = ",";

    private File messageFile;
    private File[] attachFiles;
    private InternetAddress[] toAddresses;
    private InternetAddress fromAddress;
    private String subject = "Ant notification";
    private String message;
    private String smtpHost = "localhost";

    public void setMessagefile(String msgfile) {
            messageFile = project.resolveFile(msgfile);
    }

    public void setAttachfile(String attachfile) {
        String inputArray = parseMultiple( attachfile );
        attachFiles = new String[inputArray.length];

        for( int i = 0; i < inputArray.length; i++ ) {
            attachFiles[i] = project.resolveFile( inputArray[i] );
        }
    }

    public void setMailto( String to_addr ) {
        String inputArray = parseMultiple( to_addr );
        toAddresses = new InternetAddress[ inputArray.length ];

        for( int i = 0; i < inputArray.length; i++ ) {
            try {
                toAddresses[i] = new InternetAddress( inputArray[i] );
            } catch( AddressException e ) {
                throw new BuildException( "Email: Invalid email address
supplied in mailto " + to_addr );
            }
        }
    }

    public void setMailfrom( String from_addr ) {
        try {
            fromAddress = new InternetAddress( from_addr );
        } catch( Exception e ) {
            throw new BuildException( "Email: Invalid email address supplied
in mailfrom " + from_addr );
        }
    }

    public void setSubject( String subj ) {
        subject = subj;
    }

    public void setMessage( String msg ) {
        message = msg;
    }

    public void setSmtphost( String host ) {
        smtpHost = host;
    }

    /**
     * Transforms a String with multiple entries to an array of Strings.
     * Multiple entries may be separated by either a comma or a space.
     * @param multiInput String containing multiple entries
     * @return string array of entries
     **/
    public static String[] parseMultiple( String multiInput ) {

        String[] newArray;
        Vector tokens = new Vector();

        StringTokenizer sToke = new StringTokenizer( multiInput, ", " );
        while( sToke.hasMoreElements() ) {
            tokens.addElement( sToke.nextElement() );
        }

        newArray = new String[ tokens.size() ];
        for( int i = 0; i < tokens.size(); i++ ) {
            newArray[i] = (String) tokens.elementAt( i );
        }

        return( newArray );

    }

    /**
     * Does the work.
     *
     * @exception BuildException if someting goes wrong with the build
     */
    public void execute() throws BuildException {

        if( toAddresses == null ) {
            throw new BuildException("Email: mailto is not specified");
        }

        if( fromAddress == null ) {
            throw new BuildException("Email: mailfrom is not specified" );
        }

        if( message == null && messageFile == null ) {
            throw new BuildException("Email: message and messagefile
missing, one must be present.");
        }

        // Create properties to hold smtpHost for Session.
        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);

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

        try {

            // Create a MimeMessage
            MimeMessage msg = new MimeMessage(session);

            // Set the from and to addresses
            // Set the subject and date.
            msg.setFrom( fromAddress );
            msg.setRecipients(Message.RecipientType.TO, toAddresses);
            msg.setSubject(subject);
            msg.setSentDate(new Date());

            // create the Multipart and its parts to it
            Multipart mp = new MimeMultipart();

            MimeBodyPart mbp1 = new MimeBodyPart();

            StringBuffer messageBody = new StringBuffer();

            if( message != null ) {
                messageBody.append( message );
            }

            if( messageFile != null ) {
                FileReader mFileReader = null;
                try {
                    mFileReader = new FileReader( messageFile );
                } catch( FileNotFoundException e ) {
                    throw new BuildException( "messageFile not found: " +
e.toString() );
                }

                LineNumberReader lnReader = new
ineNumberReader( mFileReader );
                String currentLine = new String();
                try {
                    messageBody.append( "\n\n********* Included File: " +
messageFile.getName() + "\n\n");
                    while( ( currentLine = lnReader.readLine() ) != null ) {
                        messageBody.append( currentLine + "\n");
                    }
                } catch( IOException e ) {
                    throw new BuildException( "IOException during
messagefile read: " + e.toString() );
                }

            }

            mbp1.setText( messageBody.toString() );
            mp.addBodyPart(mbp1);

            if( attachFiles != null ) {

                for( int i = 0; i < attachFiles.length; i++ ) {

                    // create and fill the second message part
                    MimeBodyPart mbp = new MimeBodyPart();

                    FileDataSource fds= new FileDataSource(attachFiles[i]);
                    mbp.setDataHandler(new DataHandler(fds));
                    mbp.setFileName(fds.getName());

                    // Add this file as a MIME attachment
                    mp.addBodyPart(mbp);

                }

            }

            // add the Multipart to the message
            msg.setContent(mp);

            // Send the email
            Transport.send(msg);

        } catch (MessagingException mex) {
            throw new BuildException( mex );
        }
    }
}

-----Original Message-----
From: Tim McGinn [mailto:tmcginn@itemus.com]
Sent: Wednesday, July 19, 2000 11:03 AM
To: 'ant-dev@jakarta.apache.org'
Subject: RE: cvs commit:.... MailMessage.java


To get a bit off topic, I would like to use this task.  How does it work?
It seems like a better way than me trying to use <exec /> to do it.

Thanks,
Tim

-----Original Message-----
From: Tim O'Brien [mailto:tmobrien@mindspring.com]
Sent: June 27, 2000 16:05
To: ant-dev@jakarta.apache.org
Subject: RE: cvs commit:.... MailMessage.java


Are you saying that no Apache project should use javax.mail?

Tim O'Brien

-----Original Message-----
From: Jason Hunter [mailto:jhunter@collab.net]
Sent: Tuesday, June 27, 2000 2:55 PM
To: ant-dev@jakarta.apache.org
Subject: Re: cvs commit:.... MailMessage.java


James Todd wrote:
>
> isn't it possible and most likely preferred that when there are
implementation
> choices (choices are good) to "shield" the actual mail message
implementation
> behind an adaptor or what not that is in turn intimately aware of ant?
that way,
> if javax.mail is available, as determined by the adapter at run time, an
argueably
> rich and solid extension is available but if that javax.mail is not
available then
> an alternative package is used.

But we're talking about sending a mail message.  Easy thing, standard
way to do it, just follow the RFC.  If we have an Apache-license way to
do it, I think going through the work of creating an adapter
infrastructure to allow the use of a non-freely redistributable library
is overkill.  It's not like choosing an XML parser where there are
memory/speed/compatability tradeoffs.

Now, we don't yet have an Apache-license way to do an attachment, but
adding that to MailMessage would take about as much work as writing the
adapter infrastructure, and once you were done you'd have an
Apache-license freely-redist way of doing attachments.  I view that as a
Good Thing.

If someone wants to implement an Apache-license javax.mail I wish them
good luck.  But if you're just wanting to send email, you'll spend more
time checking into the legal implications of implementing a javax.*
library than you'd spend making MailMessage do everything you want.

-jh-


Mime
View raw message