FileDocCategorySizeDatePackage
EmailTask.javaAPI DocApache Ant 1.7018283Wed Dec 13 06:16:20 GMT 2006org.apache.tools.ant.taskdefs.email

EmailTask

public class EmailTask extends org.apache.tools.ant.Task
A task to send SMTP email. This is a refactoring of the SendMail and MimeMail tasks such that both are within a single task.
since
Ant 1.5
ant.task
name="mail" category="network"

Fields Summary
public static final String
AUTO
Constant to show that the best available mailer should be used.
public static final String
MIME
Constant to allow the Mime mailer to be requested
public static final String
UU
Constant to allow the UU mailer to be requested
public static final String
PLAIN
Constant to allow the plaintext mailer to be requested
private String
encoding
private String
host
host running SMTP
private int
port
private String
subject
subject field
private Message
message
any text
private boolean
failOnError
failure flag
private boolean
includeFileNames
private String
messageMimeType
private EmailAddress
from
sender
private Vector
replyToList
replyto
private Vector
toList
TO recipients
private Vector
ccList
CC (Carbon Copy) recipients
private Vector
bccList
BCC (Blind Carbon Copy) recipients
private Vector
headers
generic headers
private org.apache.tools.ant.types.Path
attachments
file list
private String
charset
Character set for MimeMailer
private String
user
User for SMTP auth
private String
password
Password for SMTP auth
private boolean
ssl
indicate if the user wishes SSL-TLS
Constructors Summary
Methods Summary
public voidaddBcc(EmailAddress address)
Add a "bcc" address element.

param
address The email address.

        bccList.addElement(address);
    
public voidaddCc(EmailAddress address)
Add a "cc" address element.

param
address The email address.

        ccList.addElement(address);
    
public voidaddFileset(org.apache.tools.ant.types.FileSet fs)
Add a set of files (nested fileset attribute).

param
fs The fileset.

        createAttachments().add(fs);
    
public voidaddFrom(EmailAddress address)
Add a from address element.

param
address The address to send from.

        if (this.from != null) {
            throw new BuildException("Emails can only be from one address");
        }
        this.from = address;
    
public voidaddMessage(Message message)
Add a message element.

param
message The message object.
throws
BuildException if a message has already been added.

        if (this.message != null) {
            throw new BuildException(
                "Only one message can be sent in an email");
        }
        this.message = message;
    
public voidaddReplyTo(EmailAddress address)
Add a replyto address element.

param
address The address to reply to.
since
Ant 1.6

        this.replyToList.add(address);
    
public voidaddTo(EmailAddress address)
Add a to address element.

param
address An email address.

        toList.addElement(address);
    
public org.apache.tools.ant.types.PathcreateAttachments()
Creates a Path as container for attachments. Supports any filesystem resource-collections that way.

return
the path to be configured.
since
Ant 1.7

        if (attachments == null) {
            attachments = new Path(getProject());
        }
        return attachments.createPath();
    
public HeadercreateHeader()
Create a nested header element.

return
a Header instance.

        Header h = new Header();
        headers.add(h);
        return h;
    
public voidexecute()
Send an email.

        Message savedMessage = message;

        try {
            Mailer mailer = null;

            // prepare for the auto select mechanism
            boolean autoFound = false;
            // try MIME format
            if (encoding.equals(MIME)
                 || (encoding.equals(AUTO) && !autoFound)) {
                try {
                    mailer = (Mailer) ClasspathUtils.newInstance(
                            "org.apache.tools.ant.taskdefs.email.MimeMailer",
                            EmailTask.class.getClassLoader(), Mailer.class);
                    autoFound = true;
                    log("Using MIME mail", Project.MSG_VERBOSE);
                } catch (BuildException e) {
                    Throwable t = e.getCause() == null ? e : e.getCause();
                    log("Failed to initialise MIME mail: " + t.getMessage(),
                            Project.MSG_WARN);
                    return;
                }
            }
            // SMTP auth only allowed with MIME mail
            if (!autoFound && ((user != null) || (password != null))
                && (encoding.equals(UU) || encoding.equals(PLAIN))) {
                throw new BuildException("SMTP auth only possible with MIME mail");
            }
            // SSL only allowed with MIME mail
            if (!autoFound  && (ssl)
                && (encoding.equals(UU) || encoding.equals(PLAIN))) {
                throw new BuildException("SSL only possible with MIME mail");
            }
            // try UU format
            if (encoding.equals(UU)
                 || (encoding.equals(AUTO) && !autoFound)) {
                try {
                    mailer = (Mailer) ClasspathUtils.newInstance(
                            "org.apache.tools.ant.taskdefs.email.UUMailer",
                            EmailTask.class.getClassLoader(), Mailer.class);
                    autoFound = true;
                    log("Using UU mail", Project.MSG_VERBOSE);
                } catch (BuildException e) {
                    Throwable t = e.getCause() == null ? e : e.getCause();
                    log("Failed to initialise UU mail: " + t.getMessage(),
                            Project.MSG_WARN);
                    return;
                }
            }
            // try plain format
            if (encoding.equals(PLAIN)
                 || (encoding.equals(AUTO) && !autoFound)) {
                mailer = new PlainMailer();
                autoFound = true;
                log("Using plain mail", Project.MSG_VERBOSE);
            }
            // a valid mailer must be present by now
            if (mailer == null) {
                throw new BuildException("Failed to initialise encoding: "
                     + encoding);
            }
            // a valid message is required
            if (message == null) {
                message = new Message();
                message.setProject(getProject());
            }
            // an address to send from is required
            if (from == null || from.getAddress() == null) {
                throw new BuildException("A from element is required");
            }
            // at least one address to send to/cc/bcc is required
            if (toList.isEmpty() && ccList.isEmpty() && bccList.isEmpty()) {
                throw new BuildException("At least one of to, cc or bcc must "
                     + "be supplied");
            }
            // set the mimetype if not done already (and required)
            if (messageMimeType != null) {
                if (message.isMimeTypeSpecified()) {
                    throw new BuildException("The mime type can only be "
                         + "specified in one location");
                }
                message.setMimeType(messageMimeType);
            }
            // set the character set if not done already (and required)
            if (charset != null) {
                if (message.getCharset() != null) {
                    throw new BuildException("The charset can only be "
                         + "specified in one location");
                }
                message.setCharset(charset);
            }

            // identify which files should be attached
            Vector files = new Vector();
            if (attachments != null) {
                Iterator iter = attachments.iterator();

                while (iter.hasNext()) {
                    FileResource fr = (FileResource) iter.next();
                    files.addElement(fr.getFile());
                }
            }
            // let the user know what's going to happen
            log("Sending email: " + subject, Project.MSG_INFO);
            log("From " + from, Project.MSG_VERBOSE);
            log("ReplyTo " + replyToList, Project.MSG_VERBOSE);
            log("To " + toList, Project.MSG_VERBOSE);
            log("Cc " + ccList, Project.MSG_VERBOSE);
            log("Bcc " + bccList, Project.MSG_VERBOSE);

            // pass the params to the mailer
            mailer.setHost(host);
            mailer.setPort(port);
            mailer.setUser(user);
            mailer.setPassword(password);
            mailer.setSSL(ssl);
            mailer.setMessage(message);
            mailer.setFrom(from);
            mailer.setReplyToList(replyToList);
            mailer.setToList(toList);
            mailer.setCcList(ccList);
            mailer.setBccList(bccList);
            mailer.setFiles(files);
            mailer.setSubject(subject);
            mailer.setTask(this);
            mailer.setIncludeFileNames(includeFileNames);
            mailer.setHeaders(headers);

            // send the email
            mailer.send();

            // let the user know what happened
            int count = files.size();

            log("Sent email with " + count + " attachment"
                 + (count == 1 ? "" : "s"), Project.MSG_INFO);
        } catch (BuildException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            log("Failed to send email: " + t.getMessage(), Project.MSG_WARN);
            if (failOnError) {
                throw e;
            }
        } catch (Exception e) {
          log("Failed to send email: " + e.getMessage(), Project.MSG_WARN);
          if (failOnError) {
            throw new BuildException(e);
          }
        } finally {
            message = savedMessage;
        }
    
public java.lang.StringgetCharset()
Returns the character set of mail message.

return
Charset of mail message.
since
Ant 1.6

        return charset;
    
public booleangetIncludeFileNames()
Get whether file names should be included.

return
Identifies whether file names should be included.

        return includeFileNames;
    
public voidsetBccList(java.lang.String list)
Shorthand to set the "bcc" address element.

param
list comma separated list of addresses.

        StringTokenizer tokens = new StringTokenizer(list, ",");

        while (tokens.hasMoreTokens()) {
            bccList.addElement(new EmailAddress(tokens.nextToken()));
        }
    
public voidsetCcList(java.lang.String list)
Shorthand to set the "cc" address element.

param
list Comma separated list of addresses.

        StringTokenizer tokens = new StringTokenizer(list, ",");

        while (tokens.hasMoreTokens()) {
            ccList.addElement(new EmailAddress(tokens.nextToken()));
        }
    
public voidsetCharset(java.lang.String charset)
Sets the character set of mail message. Will be ignored if mimeType contains ....; Charset=... substring or encoding is not a mime.

param
charset the character encoding to use.
since
Ant 1.6

        this.charset = charset;
    
public voidsetEncoding(org.apache.tools.ant.taskdefs.email.EmailTask$Encoding encoding)
Set the preferred encoding method.

param
encoding The encoding (one of AUTO, MIME, UU, PLAIN).

        this.encoding = encoding.getValue();
    
public voidsetFailOnError(boolean failOnError)
Set whether BuildExceptions should be passed back to the core.

param
failOnError The new FailOnError value.

        this.failOnError = failOnError;
    
public voidsetFiles(java.lang.String filenames)
Set the list of files to be attached.

param
filenames Comma-separated list of files.

        StringTokenizer t = new StringTokenizer(filenames, ", ");

        while (t.hasMoreTokens()) {
            createAttachments()
                .add(new FileResource(getProject().resolveFile(t.nextToken())));
        }
    
public voidsetFrom(java.lang.String address)
Shorthand to set the from address element.

param
address The address to send mail from.

        if (this.from != null) {
            throw new BuildException("Emails can only be from one address");
        }
        this.from = new EmailAddress(address);
    
public voidsetIncludefilenames(boolean includeFileNames)
Set whether to include filenames.

param
includeFileNames Whether to include filenames in the text of the message.

        this.includeFileNames = includeFileNames;
    
public voidsetMailhost(java.lang.String host)
Set the host.

param
host The host to connect to.

        this.host = host;
    
public voidsetMailport(int port)
Set the mail server port.

param
port The port to use.

        this.port = port;
    
public voidsetMessage(java.lang.String message)
Shorthand method to set the message.

param
message Message body of this email.

        if (this.message != null) {
            throw new BuildException("Only one message can be sent in an "
                 + "email");
        }
        this.message = new Message(message);
        this.message.setProject(getProject());
    
public voidsetMessageFile(java.io.File file)
Shorthand method to set the message from a file.

param
file The file from which to take the message.

        if (this.message != null) {
            throw new BuildException("Only one message can be sent in an "
                 + "email");
        }
        this.message = new Message(file);
        this.message.setProject(getProject());
    
public voidsetMessageMimeType(java.lang.String type)
Shorthand method to set type of the text message, text/plain by default but text/html or text/xml is quite feasible.

param
type The new MessageMimeType value.

        this.messageMimeType = type;
    
public voidsetPassword(java.lang.String password)
Set the password for SMTP auth; this requires JavaMail.

param
password the String password.
since
Ant 1.6

        this.password = password;
    
public voidsetReplyTo(java.lang.String address)
Shorthand to set the replyto address element.

param
address The address to which replies should be directed.
since
Ant 1.6

        this.replyToList.add(new EmailAddress(address));
    
public voidsetSSL(boolean ssl)
Set whether to send data over SSL.

param
ssl boolean; if true SSL will be used.
since
Ant 1.6

        this.ssl = ssl;
    
public voidsetSubject(java.lang.String subject)
Set the subject line of the email.

param
subject Subject of this email.

        this.subject = subject;
    
public voidsetToList(java.lang.String list)
Shorthand to set the "to" address element.

param
list Comma-separated list of addresses.

        StringTokenizer tokens = new StringTokenizer(list, ",");

        while (tokens.hasMoreTokens()) {
            toList.addElement(new EmailAddress(tokens.nextToken()));
        }
    
public voidsetUser(java.lang.String user)
Set the user for SMTP auth; this requires JavaMail.

param
user the String username.
since
Ant 1.6


                          
        
        this.user = user;