Browse Source

Add nested header element to the mail task.

PR: 24713


git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@277575 13f79535-47bb-0310-9956-ffa450edef68
master
Matthew Jason Benson 20 years ago
parent
commit
f5b5a8b53c
7 changed files with 306 additions and 246 deletions
  1. +2
    -0
      WHATSNEW
  2. +26
    -1
      docs/manual/CoreTasks/mail.html
  3. +90
    -117
      src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java
  4. +60
    -0
      src/main/org/apache/tools/ant/taskdefs/email/Header.java
  5. +44
    -45
      src/main/org/apache/tools/ant/taskdefs/email/Mailer.java
  6. +77
    -72
      src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java
  7. +7
    -11
      src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java

+ 2
- 0
WHATSNEW View File

@@ -99,6 +99,8 @@ Other changes:


* ant -diagnostics lists contents of ${user.home}/.ant/lib * ant -diagnostics lists contents of ${user.home}/.ant/lib


* mail task accepts nested header element. Bugzilla report 24713.

Changes from Ant 1.6.2 to current Ant 1.6 CVS version Changes from Ant 1.6.2 to current Ant 1.6 CVS version
===================================================== =====================================================




+ 26
- 1
docs/manual/CoreTasks/mail.html View File

@@ -212,6 +212,31 @@ inside the <code>&lt;message&gt;</code> element. Property expansion will occur
in the message, whether it is specified as an external file or as text within in the message, whether it is specified as an external file or as text within
the <code>&lt;message&gt;</code> element.</p> the <code>&lt;message&gt;</code> element.</p>


<h4>header</h4>
<p><strong>Since Ant 1.7</strong>, arbitrary mail headers can be added by
specifying these attributes on one or more nested header elements:</p>

<table width="60%" border="1" cellpadding="2" cellspacing="0">
<tr>
<td valign="top"><b>Attribute</b></td>
<td valign="top"><b>Description</b></td>
<td align="center" valign="top"><b>Required</b></td>
</tr>
<tr>
<td valign="top">name</td>
<td valign="top">The name associated with this mail header.</td>
<td align="center" valign="top">Yes</td>
</tr>
<tr>
<td valign="top">value</td>
<td valign="top">The value to assign to this mail header.</td>
<td align="center" valign="top">Yes</td>
</tr>
</table>

<p>It is permissible to duplicate the name attribute amongst multiple headers.
</p>

<h3>Examples</h3> <h3>Examples</h3>


<blockquote><pre> <blockquote><pre>
@@ -259,7 +284,7 @@ will be replaced with the <code>buildname</code> property's value.</p>
<i>Test Build</i>, the message body being coded in UTF-8 <i>Test Build</i>, the message body being coded in UTF-8


<hr> <hr>
<p align="center">Copyright &copy; 2000-2004 The Apache Software Foundation. All rights
<p align="center">Copyright &copy; 2000-2005 The Apache Software Foundation. All rights
Reserved.</p> Reserved.</p>


</body> </body>


+ 90
- 117
src/main/org/apache/tools/ant/taskdefs/email/EmailTask.java View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2000-2004 The Apache Software Foundation
* Copyright 2000-2005 The Apache Software Foundation
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,12 +16,11 @@
*/ */
package org.apache.tools.ant.taskdefs.email; package org.apache.tools.ant.taskdefs.email;


// Ant imports

import java.io.File; import java.io.File;
import java.util.Vector;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project; import org.apache.tools.ant.Project;
@@ -36,8 +35,7 @@ import org.apache.tools.ant.types.FileSet;
* @since Ant 1.5 * @since Ant 1.5
* @ant.task name="mail" category="network" * @ant.task name="mail" category="network"
*/ */
public class EmailTask
extends Task {
public class EmailTask extends Task {
/** Constant to show that the best available mailer should be used. */ /** Constant to show that the best available mailer should be used. */
public static final String AUTO = "auto"; public static final String AUTO = "auto";
/** Constant to allow the Mime mailer to be requested */ /** Constant to allow the Mime mailer to be requested */
@@ -47,9 +45,8 @@ public class EmailTask
/** Constant to allow the plaintext mailer to be requested */ /** Constant to allow the plaintext mailer to be requested */
public static final String PLAIN = "plain"; public static final String PLAIN = "plain";



/** /**
* Enumerates the encoding constants
* Enumerates the encoding constants.
*/ */
public static class Encoding extends EnumeratedAttribute { public static class Encoding extends EnumeratedAttribute {
/** /**
@@ -74,7 +71,7 @@ public class EmailTask
private boolean failOnError = true; private boolean failOnError = true;
private boolean includeFileNames = false; private boolean includeFileNames = false;
private String messageMimeType = null; private String messageMimeType = null;
/** special headers */
/* special headers */
/** sender */ /** sender */
private EmailAddress from = null; private EmailAddress from = null;
/** replyto */ /** replyto */
@@ -86,6 +83,9 @@ public class EmailTask
/** BCC (Blind Carbon Copy) recipients */ /** BCC (Blind Carbon Copy) recipients */
private Vector bccList = new Vector(); private Vector bccList = new Vector();


/** generic headers */
private Vector headers = new Vector();

/** file list */ /** file list */
private Vector files = new Vector(); private Vector files = new Vector();
private Vector filesets = new Vector(); private Vector filesets = new Vector();
@@ -99,64 +99,61 @@ public class EmailTask
private boolean SSL = false; private boolean SSL = false;


/** /**
* sets the user for SMTP auth; this requires JavaMail
* @param user
* @since ant 1.6
* Set the user for SMTP auth; this requires JavaMail.
* @param user the String username.
* @since Ant 1.6
*/ */
public void setUser(String user) { public void setUser(String user) {
this.user = user; this.user = user;
} }


/** /**
* sets the password for SMTP auth; this requires JavaMail
* @param password
* @since ant 1.6
* Set the password for SMTP auth; this requires JavaMail.
* @param password the String password.
* @since Ant 1.6
*/ */
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }


/** /**
* tells if the user needs to send his data over SSL
* @param SSL
* @since ant 1.6
* Set whether to send data over SSL.
* @param SSL boolean; if true SSL will be used.
* @since Ant 1.6
*/ */
public void setSSL(boolean SSL) { public void setSSL(boolean SSL) {
this.SSL = SSL; this.SSL = SSL;
} }


/** /**
* Allows the build writer to choose the preferred encoding method
* Set the preferred encoding method.
* *
* @param encoding The encoding (one of AUTO,MIME,UU,PLAIN)
* @param encoding The encoding (one of AUTO, MIME, UU, PLAIN).
*/ */
public void setEncoding(Encoding encoding) { public void setEncoding(Encoding encoding) {
this.encoding = encoding.getValue(); this.encoding = encoding.getValue();
} }



/** /**
* Sets the mail server port
* Set the mail server port.
* *
* @param port The port to use
* @param port The port to use.
*/ */
public void setMailport(int port) { public void setMailport(int port) {
this.port = port; this.port = port;
} }



/** /**
* Sets the host
* Set the host.
* *
* @param host The host to connect to
* @param host The host to connect to.
*/ */
public void setMailhost(String host) { public void setMailhost(String host) {
this.host = host; this.host = host;
} }



/** /**
* Sets the subject line of the email
* Set the subject line of the email.
* *
* @param subject Subject of this email. * @param subject Subject of this email.
*/ */
@@ -164,9 +161,8 @@ public class EmailTask
this.subject = subject; this.subject = subject;
} }



/** /**
* Shorthand method to set the message
* Shorthand method to set the message.
* *
* @param message Message body of this email. * @param message Message body of this email.
*/ */
@@ -175,120 +171,105 @@ public class EmailTask
throw new BuildException("Only one message can be sent in an " throw new BuildException("Only one message can be sent in an "
+ "email"); + "email");
} }

this.message = new Message(message); this.message = new Message(message);
this.message.setProject(getProject()); this.message.setProject(getProject());
} }



/** /**
* Shorthand method to set the message from a file
* Shorthand method to set the message from a file.
* *
* @param file The file from which to take the message
* @param file The file from which to take the message.
*/ */
public void setMessageFile(File file) { public void setMessageFile(File file) {
if (this.message != null) { if (this.message != null) {
throw new BuildException("Only one message can be sent in an " throw new BuildException("Only one message can be sent in an "
+ "email"); + "email");
} }

this.message = new Message(file); this.message = new Message(file);
this.message.setProject(getProject()); this.message.setProject(getProject());
} }



/** /**
* Shorthand method to set type of the text message, text/plain by default * Shorthand method to set type of the text message, text/plain by default
* but text/html or text/xml is quite feasible. * but text/html or text/xml is quite feasible.
* *
* @param type The new MessageMimeType value
* @param type The new MessageMimeType value.
*/ */
public void setMessageMimeType(String type) { public void setMessageMimeType(String type) {
this.messageMimeType = type; this.messageMimeType = type;
} }



/** /**
* Add a message element
* Add a message element.
* *
* @param message The message object
* @throws BuildException if a message has already been added
* @param message The message object.
* @throws BuildException if a message has already been added.
*/ */
public void addMessage(Message message)
throws BuildException {
public void addMessage(Message message) throws BuildException {
if (this.message != null) { if (this.message != null) {
throw new BuildException("Only one message can be sent in an "
+ "email");
throw new BuildException(
"Only one message can be sent in an email");
} }

this.message = message; this.message = message;
} }



/** /**
* Adds a from address element
* Add a from address element.
* *
* @param address The address to send from
* @param address The address to send from.
*/ */
public void addFrom(EmailAddress address) { public void addFrom(EmailAddress address) {
if (this.from != null) { if (this.from != null) {
throw new BuildException("Emails can only be from one address"); throw new BuildException("Emails can only be from one address");
} }

this.from = address; this.from = address;
} }



/** /**
* Shorthand to set the from address element
* Shorthand to set the from address element.
* *
* @param address The address to send mail from
* @param address The address to send mail from.
*/ */
public void setFrom(String address) { public void setFrom(String address) {
if (this.from != null) { if (this.from != null) {
throw new BuildException("Emails can only be from one address"); throw new BuildException("Emails can only be from one address");
} }

this.from = new EmailAddress(address); this.from = new EmailAddress(address);
} }



/** /**
* Adds a replyto address element
* Add a replyto address element.
* *
* @param address The address to reply to
* @since ant 1.6
* @param address The address to reply to.
* @since Ant 1.6
*/ */
public void addReplyTo(EmailAddress address) { public void addReplyTo(EmailAddress address) {
this.replyToList.add(address); this.replyToList.add(address);
} }



/** /**
* Shorthand to set the replyto address element
* Shorthand to set the replyto address element.
* *
* @param address The address to which replies should be directed
* @since ant 1.6
* @param address The address to which replies should be directed.
* @since Ant 1.6
*/ */
public void setReplyTo(String address) { public void setReplyTo(String address) {
this.replyToList.add(new EmailAddress(address)); this.replyToList.add(new EmailAddress(address));
} }



/** /**
* Adds a to address element
* Add a to address element.
* *
* @param address An email address
* @param address An email address.
*/ */
public void addTo(EmailAddress address) { public void addTo(EmailAddress address) {
toList.addElement(address); toList.addElement(address);
} }



/** /**
* Adds "to" address elements
* Shorthand to set the "to" address element.
* *
* @param list Comma separated list of addresses
* @param list Comma-separated list of addresses.
*/ */
public void setToList(String list) { public void setToList(String list) {
StringTokenizer tokens = new StringTokenizer(list, ","); StringTokenizer tokens = new StringTokenizer(list, ",");
@@ -298,21 +279,19 @@ public class EmailTask
} }
} }



/** /**
* Adds "cc" address element
* Add a "cc" address element.
* *
* @param address The email address
* @param address The email address.
*/ */
public void addCc(EmailAddress address) { public void addCc(EmailAddress address) {
ccList.addElement(address); ccList.addElement(address);
} }



/** /**
* Adds "cc" address elements
* Shorthand to set the "cc" address element.
* *
* @param list Comma separated list of addresses
* @param list Comma separated list of addresses.
*/ */
public void setCcList(String list) { public void setCcList(String list) {
StringTokenizer tokens = new StringTokenizer(list, ","); StringTokenizer tokens = new StringTokenizer(list, ",");
@@ -322,21 +301,19 @@ public class EmailTask
} }
} }



/** /**
* Adds "bcc" address elements
* Add a "bcc" address element.
* *
* @param address The email address
* @param address The email address.
*/ */
public void addBcc(EmailAddress address) { public void addBcc(EmailAddress address) {
bccList.addElement(address); bccList.addElement(address);
} }



/** /**
* Adds "bcc" address elements
* Shorthand to set the "bcc" address element.
* *
* @param list comma separated list of addresses
* @param list comma separated list of addresses.
*/ */
public void setBccList(String list) { public void setBccList(String list) {
StringTokenizer tokens = new StringTokenizer(list, ","); StringTokenizer tokens = new StringTokenizer(list, ",");
@@ -346,21 +323,19 @@ public class EmailTask
} }
} }



/** /**
* Indicates whether BuildExceptions should be passed back to the core
* Set whether BuildExceptions should be passed back to the core.
* *
* @param failOnError The new FailOnError value
* @param failOnError The new FailOnError value.
*/ */
public void setFailOnError(boolean failOnError) { public void setFailOnError(boolean failOnError) {
this.failOnError = failOnError; this.failOnError = failOnError;
} }



/** /**
* Adds a list of files to be attached
* Set the list of files to be attached.
* *
* @param filenames Comma separated list of files
* @param filenames Comma-separated list of files.
*/ */
public void setFiles(String filenames) { public void setFiles(String filenames) {
StringTokenizer t = new StringTokenizer(filenames, ", "); StringTokenizer t = new StringTokenizer(filenames, ", ");
@@ -370,39 +345,47 @@ public class EmailTask
} }
} }



/** /**
* Adds a set of files (nested fileset attribute).
* Add a set of files (nested fileset attribute).
* *
* @param fs The fileset
* @param fs The fileset.
*/ */
public void addFileset(FileSet fs) { public void addFileset(FileSet fs) {
filesets.addElement(fs); filesets.addElement(fs);
} }


/**
* Create a nested header element.
* @return a Header instance.
*/
public Header createHeader() {
Header h = new Header();
headers.add(h);
return h;
}


/** /**
* Sets Includefilenames attribute
* Set whether to include filenames.
* *
* @param includeFileNames Whether to include filenames in the text of the * @param includeFileNames Whether to include filenames in the text of the
* message
* message.
*/ */
public void setIncludefilenames(boolean includeFileNames) { public void setIncludefilenames(boolean includeFileNames) {
this.includeFileNames = includeFileNames; this.includeFileNames = includeFileNames;
} }



/** /**
* Identifies whether file names should be included
* Get whether file names should be included.
* *
* @return Identifies whether file names should be included
* @return Identifies whether file names should be included.
*/ */
public boolean getIncludeFileNames() { public boolean getIncludeFileNames() {
return includeFileNames; return includeFileNames;
} }



/** Sends an email */
/**
* Send an email.
*/
public void execute() { public void execute() {
Message savedMessage = message; Message savedMessage = message;
Vector savedFiles = (Vector) files.clone(); Vector savedFiles = (Vector) files.clone();
@@ -416,8 +399,8 @@ public class EmailTask
if (encoding.equals(MIME) if (encoding.equals(MIME)
|| (encoding.equals(AUTO) && !autoFound)) { || (encoding.equals(AUTO) && !autoFound)) {
try { try {
mailer =
(Mailer) Class.forName("org.apache.tools.ant.taskdefs.email.MimeMailer")
mailer = (Mailer) Class.forName(
"org.apache.tools.ant.taskdefs.email.MimeMailer")
.newInstance(); .newInstance();
autoFound = true; autoFound = true;
log("Using MIME mail", Project.MSG_VERBOSE); log("Using MIME mail", Project.MSG_VERBOSE);
@@ -436,8 +419,6 @@ public class EmailTask
&& (encoding.equals(UU) || encoding.equals(PLAIN))) { && (encoding.equals(UU) || encoding.equals(PLAIN))) {
throw new BuildException("SSL only possible with MIME mail"); throw new BuildException("SSL only possible with MIME mail");
} }


// try UU format // try UU format
if (encoding.equals(UU) if (encoding.equals(UU)
|| (encoding.equals(AUTO) && !autoFound)) { || (encoding.equals(AUTO) && !autoFound)) {
@@ -451,7 +432,6 @@ public class EmailTask
log("Failed to initialise UU mail", Project.MSG_WARN); log("Failed to initialise UU mail", Project.MSG_WARN);
} }
} }

// try plain format // try plain format
if (encoding.equals(PLAIN) if (encoding.equals(PLAIN)
|| (encoding.equals(AUTO) && !autoFound)) { || (encoding.equals(AUTO) && !autoFound)) {
@@ -459,49 +439,41 @@ public class EmailTask
autoFound = true; autoFound = true;
log("Using plain mail", Project.MSG_VERBOSE); log("Using plain mail", Project.MSG_VERBOSE);
} }

// a valid mailer must be present by now // a valid mailer must be present by now
if (mailer == null) { if (mailer == null) {
throw new BuildException("Failed to initialise encoding: " throw new BuildException("Failed to initialise encoding: "
+ encoding); + encoding);
} }

// a valid message is required // a valid message is required
if (message == null) { if (message == null) {
message = new Message(); message = new Message();
message.setProject(getProject()); message.setProject(getProject());
} }

// an address to send from is required // an address to send from is required
if (from == null || from.getAddress() == null) { if (from == null || from.getAddress() == null) {
throw new BuildException("A from element is required"); throw new BuildException("A from element is required");
} }

// at least one address to send to/cc/bcc is required // at least one address to send to/cc/bcc is required
if (toList.isEmpty() && ccList.isEmpty() && bccList.isEmpty()) { if (toList.isEmpty() && ccList.isEmpty() && bccList.isEmpty()) {
throw new BuildException("At least one of to,cc or bcc must "
throw new BuildException("At least one of to, cc or bcc must "
+ "be supplied"); + "be supplied");
} }

// set the mimetype if not done already (and required) // set the mimetype if not done already (and required)
if (messageMimeType != null) { if (messageMimeType != null) {
if (message.isMimeTypeSpecified()) { if (message.isMimeTypeSpecified()) {
throw new BuildException("The mime type can only be " throw new BuildException("The mime type can only be "
+ "specified in one location"); + "specified in one location");
} else {
message.setMimeType(messageMimeType);
} }
message.setMimeType(messageMimeType);
} }
// set the character set if not done already (and required) // set the character set if not done already (and required)
if (charset != null) { if (charset != null) {
if (message.getCharset() != null) { if (message.getCharset() != null) {
throw new BuildException("The charset can only be " throw new BuildException("The charset can only be "
+ "specified in one location"); + "specified in one location");
} else {
message.setCharset(charset);
} }
message.setCharset(charset);
} }

// identify which files should be attached // identify which files should be attached
Enumeration e = filesets.elements(); Enumeration e = filesets.elements();


@@ -513,12 +485,9 @@ public class EmailTask
File baseDir = ds.getBasedir(); File baseDir = ds.getBasedir();


for (int j = 0; j < includedFiles.length; ++j) { for (int j = 0; j < includedFiles.length; ++j) {
File file = new File(baseDir, includedFiles[j]);

files.addElement(file);
files.addElement(new File(baseDir, includedFiles[j]));
} }
} }

// let the user know what's going to happen // let the user know what's going to happen
log("Sending email: " + subject, Project.MSG_INFO); log("Sending email: " + subject, Project.MSG_INFO);
log("From " + from, Project.MSG_VERBOSE); log("From " + from, Project.MSG_VERBOSE);
@@ -543,6 +512,7 @@ public class EmailTask
mailer.setSubject(subject); mailer.setSubject(subject);
mailer.setTask(this); mailer.setTask(this);
mailer.setIncludeFileNames(includeFileNames); mailer.setIncludeFileNames(includeFileNames);
mailer.setHeaders(headers);


// send the email // send the email
mailer.send(); mailer.send();
@@ -567,15 +537,17 @@ public class EmailTask
files = savedFiles; files = savedFiles;
} }
} }

/** /**
* Sets the character set of mail message. * Sets the character set of mail message.
* Will be ignored if mimeType contains ....; Charset=... substring or * Will be ignored if mimeType contains ....; Charset=... substring or
* encoding is not a <code>mime</code>
* encoding is not a <code>mime</code>.
* @since Ant 1.6 * @since Ant 1.6
*/ */
public void setCharset(String charset) { public void setCharset(String charset) {
this.charset = charset; this.charset = charset;
} }

/** /**
* Returns the character set of mail message. * Returns the character set of mail message.
* *
@@ -585,5 +557,6 @@ public class EmailTask
public String getCharset() { public String getCharset() {
return charset; return charset;
} }

} }



+ 60
- 0
src/main/org/apache/tools/ant/taskdefs/email/Header.java View File

@@ -0,0 +1,60 @@
/*
* Copyright 2005 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.taskdefs.email;

/**
* Class representing a generic e-mail header.
* @since Ant 1.7
*/
public class Header {
private String name;
private String value;

/**
* Set the name of this Header.
* @param name the name to set.
*/
public void setName(String name) {
this.name = name;
}

/**
* Get the name of this Header.
* @return name as String.
*/
public String getName() {
return name;
}

/**
* Set the value of this Header.
* @param value the value to set.
*/
public void setValue(String value) {
this.value = value;
}

/**
* Get the value of this Header.
* @return value as String.
*/
public String getValue() {
return value;
}

}

+ 44
- 45
src/main/org/apache/tools/ant/taskdefs/email/Mailer.java View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2004 The Apache Software Foundation
* Copyright 2002-2005 The Apache Software Foundation
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -42,119 +42,113 @@ public abstract class Mailer {
protected String subject = null; protected String subject = null;
protected Task task; protected Task task;
protected boolean includeFileNames = false; protected boolean includeFileNames = false;
protected Vector headers = null;


/** /**
* Sets the mail server
* Set the mail server.
* *
* @param host the mail server name
* @param host the mail server name.
*/ */
public void setHost(String host) { public void setHost(String host) {
this.host = host; this.host = host;
} }



/** /**
* Sets the smtp port
* Set the smtp port.
* *
* @param port the SMTP port
* @param port the SMTP port.
*/ */
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
} }


/** /**
* Sets the user for smtp auth
* Set the user for smtp auth.
* *
* @param user the username
* @since ant 1.6
* @param user the username.
* @since Ant 1.6
*/ */
public void setUser(String user) { public void setUser(String user) {
this.user = user; this.user = user;
} }


/** /**
* Sets the password for smtp auth
* Set the password for smtp auth.
* *
* @param password the authentication password
* @since ant 1.6
* @param password the authentication password.
* @since Ant 1.6
*/ */
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }


/** /**
* Sets whether the user wants to send the mail through SSL
* Set whether to send the mail through SSL.
* *
* @param SSL if true use SSL transport
* @since ant 1.6
* @param SSL if true use SSL transport.
* @since Ant 1.6
*/ */
public void setSSL(boolean SSL) { public void setSSL(boolean SSL) {
this.SSL = SSL; this.SSL = SSL;
} }


/** /**
* Sets the message
* Set the message.
* *
* @param m the message content
* @param m the message content.
*/ */
public void setMessage(Message m) { public void setMessage(Message m) {
this.message = m; this.message = m;
} }



/** /**
* Sets the address to send from
* Set the address to send from.
* *
* @param from the sender
* @param from the sender.
*/ */
public void setFrom(EmailAddress from) { public void setFrom(EmailAddress from) {
this.from = from; this.from = from;
} }



/** /**
* Sets the replyto addresses
* Set the replyto addresses.
* *
* @param list a vector of reployTo addresses
* @since ant 1.6
* @param list a vector of reployTo addresses.
* @since Ant 1.6
*/ */
public void setReplyToList(Vector list) { public void setReplyToList(Vector list) {
this.replyToList = list; this.replyToList = list;
} }



/** /**
* Set the to addresses
* Set the to addresses.
* *
* @param list a vector of recipient addresses
* @param list a vector of recipient addresses.
*/ */
public void setToList(Vector list) { public void setToList(Vector list) {
this.toList = list; this.toList = list;
} }



/** /**
* Sets the cc addresses
* Set the cc addresses.
* *
* @param list a vector of cc addresses
* @param list a vector of cc addresses.
*/ */
public void setCcList(Vector list) { public void setCcList(Vector list) {
this.ccList = list; this.ccList = list;
} }



/** /**
* Sets the bcc addresses
* Set the bcc addresses.
* *
* @param list a vector of the bcc addresses
* @param list a vector of the bcc addresses.
*/ */
public void setBccList(Vector list) { public void setBccList(Vector list) {
this.bccList = list; this.bccList = list;
} }



/** /**
* Sets the files to attach
* Set the files to attach.
* *
* @param files list of files to attach to the email. * @param files list of files to attach to the email.
*/ */
@@ -162,29 +156,26 @@ public abstract class Mailer {
this.files = files; this.files = files;
} }



/** /**
* Sets the subject
* Set the subject.
* *
* @param subject the subject line
* @param subject the subject line.
*/ */
public void setSubject(String subject) { public void setSubject(String subject) {
this.subject = subject; this.subject = subject;
} }



/** /**
* Sets the owning task
* Set the owning task.
* *
* @param task the owning task instance
* @param task the owning task instance.
*/ */
public void setTask(Task task) { public void setTask(Task task) {
this.task = task; this.task = task;
} }



/** /**
* Indicates whether filenames should be listed in the body
* Indicate whether filenames should be listed in the body.
* *
* @param b if true list attached file names in the body content. * @param b if true list attached file names in the body content.
*/ */
@@ -192,9 +183,17 @@ public abstract class Mailer {
this.includeFileNames = b; this.includeFileNames = b;
} }


/**
* Set the generic headers to add to the email.
* @param v a Vector presumed to contain Header objects.
* @since Ant 1.7
*/
public void setHeaders(Vector v) {
this.headers = v;
}


/** /**
* This method should send the email
* Send the email.
* *
* @throws BuildException if the email can't be sent. * @throws BuildException if the email can't be sent.
*/ */
@@ -202,7 +201,7 @@ public abstract class Mailer {
throws BuildException; throws BuildException;


/** /**
* Returns the current Date in a format suitable for a SMTP date
* Return the current Date in a format suitable for a SMTP date
* header. * header.
* *
* @return the current date in SMTP suitable format. * @return the current date in SMTP suitable format.


+ 77
- 72
src/main/org/apache/tools/ant/taskdefs/email/MimeMailer.java View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2004 The Apache Software Foundation
* Copyright 2002-2005 The Apache Software Foundation
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,36 +16,38 @@
*/ */
package org.apache.tools.ant.taskdefs.email; package org.apache.tools.ant.taskdefs.email;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;


import java.util.Enumeration;
import java.util.Vector;
import java.util.Iterator;
import java.util.Properties; import java.util.Properties;
import java.util.Enumeration;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.Vector;
import java.security.Security;

import java.security.Provider; import java.security.Provider;
import java.security.Security;


import javax.activation.DataHandler; import javax.activation.DataHandler;
import javax.activation.FileDataSource; import javax.activation.FileDataSource;


import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message; import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport; import javax.mail.Transport;
import javax.mail.Authenticator;
import javax.mail.MessagingException; import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeMultipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;


import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildException;


@@ -62,59 +64,65 @@ public class MimeMailer extends Mailer {
// To work properly with national charsets we have to use // To work properly with national charsets we have to use
// implementation of interface javax.activation.DataSource // implementation of interface javax.activation.DataSource
/** /**
* String data source implementation.
* @since Ant 1.6 * @since Ant 1.6
*/ */
class StringDataSource implements javax.activation.DataSource { class StringDataSource implements javax.activation.DataSource {
private String data = null;
private String type = null;
private String charset = null;
private ByteArrayOutputStream out;

public InputStream getInputStream() throws IOException {
if (data == null && out == null) {
throw new IOException("No data");
} else {
if (out != null) {
data = (data != null) ? data.concat(out.toString(charset)) : out.toString(charset);
out = null;
}
return new ByteArrayInputStream(data.getBytes(charset));
private String data = null;
private String type = null;
private String charset = null;
private ByteArrayOutputStream out;

public InputStream getInputStream() throws IOException {
if (data == null && out == null) {
throw new IOException("No data");
}
if (out != null) {
String encodedOut = out.toString(charset);
data = (data != null) ? data.concat(encodedOut) : encodedOut;
out = null;
}
return new ByteArrayInputStream(data.getBytes(charset));
}

public OutputStream getOutputStream() throws IOException {
out = (out == null) ? new ByteArrayOutputStream() : out;
return out;
} }
}


public OutputStream getOutputStream() throws IOException {
if (out == null) {
out = new ByteArrayOutputStream();
public void setContentType(String type) {
this.type = type.toLowerCase();
} }
return out;
}


public void setContentType(String type) {
this.type = type.toLowerCase();
}
public String getContentType() {
if (type != null && type.indexOf("charset") > 0
&& type.startsWith("text/")) {
return type;
}
// Must be like "text/plain; charset=windows-1251"
return new StringBuffer(type != null ? type : "text/plain").append(
"; charset=").append(charset).toString();
}

public String getName() {
return "StringDataSource";
}

public void setCharset(String charset) {
this.charset = charset;
}


public String getContentType() {
if (type != null && type.indexOf("charset") > 0 && type.startsWith("text/")) {
return type;
public String getCharset() {
return charset;
} }
// Must be like "text/plain; charset=windows-1251"
return type != null ? type.concat("; charset=".concat(charset))
: "text/plain".concat("; charset=".concat(charset));
}

public String getName() {
return "StringDataSource";
}
public void setCharset(String charset) {
this.charset = charset;
}
public String getCharset() {
return charset;
}
}

/** Sends the email */
public void send() {
}

/**
* Send the email.
*
* @throws BuildException if the email can't be sent.
*/
public void send() {
try { try {
Properties props = new Properties(); Properties props = new Properties();


@@ -128,8 +136,8 @@ public class MimeMailer extends Mailer {
Authenticator auth; Authenticator auth;
if (SSL) { if (SSL) {
try { try {
Provider p
= (Provider) Class.forName("com.sun.net.ssl.internal.ssl.Provider").newInstance();
Provider p = (Provider) Class.forName(
"com.sun.net.ssl.internal.ssl.Provider").newInstance();
Security.addProvider(p); Security.addProvider(p);
} catch (Exception e) { } catch (Exception e) {
throw new BuildException("could not instantiate ssl " throw new BuildException("could not instantiate ssl "
@@ -183,7 +191,6 @@ public class MimeMailer extends Mailer {
message.setCharset(charset); message.setCharset(charset);
} }
} }

// Using javax.activation.DataSource paradigm // Using javax.activation.DataSource paradigm
StringDataSource sds = new StringDataSource(); StringDataSource sds = new StringDataSource();
sds.setContentType(message.getMimeType()); sds.setContentType(message.getMimeType());
@@ -194,6 +201,10 @@ public class MimeMailer extends Mailer {
} }
msg.addHeader("Date", getDate()); msg.addHeader("Date", getDate());


for (Iterator iter = headers.iterator(); iter.hasNext();) {
Header h = (Header) iter.next();
msg.addHeader(h.getName(), h.getValue());
}
PrintStream out = new PrintStream(sds.getOutputStream()); PrintStream out = new PrintStream(sds.getOutputStream());
message.print(out); message.print(out);
out.close(); out.close();
@@ -222,7 +233,6 @@ public class MimeMailer extends Mailer {
body.setFileName(file.getName()); body.setFileName(file.getName());
attachments.addBodyPart(body); attachments.addBodyPart(body);
} }

msg.setContent(attachments); msg.setContent(attachments);
Transport.send(msg); Transport.send(msg);
} catch (MessagingException e) { } catch (MessagingException e) {
@@ -232,24 +242,19 @@ public class MimeMailer extends Mailer {
} }
} }



private static InternetAddress[] internetAddresses(Vector list) private static InternetAddress[] internetAddresses(Vector list)
throws AddressException, UnsupportedEncodingException {
throws AddressException, UnsupportedEncodingException {
InternetAddress[] addrs = new InternetAddress[list.size()]; InternetAddress[] addrs = new InternetAddress[list.size()];


for (int i = 0; i < list.size(); ++i) { for (int i = 0; i < list.size(); ++i) {
EmailAddress addr = (EmailAddress) list.elementAt(i); EmailAddress addr = (EmailAddress) list.elementAt(i);


if (addr.getName() == null) {
addrs[i] = new InternetAddress(addr.getAddress());
} else {
addrs[i] = new InternetAddress(addr.getAddress(),
addr.getName());
}
String name = addr.getName();
addrs[i] = (name == null)
? new InternetAddress(addr.getAddress())
: new InternetAddress(addr.getAddress(), name);
} }

return addrs; return addrs;

} }


private String parseCharSetFromMimeType(String type) { private String parseCharSetFromMimeType(String type) {


+ 7
- 11
src/main/org/apache/tools/ant/taskdefs/email/PlainMailer.java View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2004 The Apache Software Foundation
* Copyright 2002-2005 The Apache Software Foundation
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -48,44 +48,40 @@ class PlainMailer extends Mailer {
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
mailMessage.replyto(e.nextElement().toString()); mailMessage.replyto(e.nextElement().toString());
} }

e = toList.elements(); e = toList.elements();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
mailMessage.to(e.nextElement().toString()); mailMessage.to(e.nextElement().toString());
} }

e = ccList.elements(); e = ccList.elements();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
mailMessage.cc(e.nextElement().toString()); mailMessage.cc(e.nextElement().toString());
} }

e = bccList.elements(); e = bccList.elements();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
mailMessage.bcc(e.nextElement().toString()); mailMessage.bcc(e.nextElement().toString());
} }

if (subject != null) { if (subject != null) {
mailMessage.setSubject(subject); mailMessage.setSubject(subject);
} }

mailMessage.setHeader("Date", getDate()); mailMessage.setHeader("Date", getDate());
if (message.getCharset() != null) { if (message.getCharset() != null) {
mailMessage.setHeader("Content-Type", message.getMimeType() mailMessage.setHeader("Content-Type", message.getMimeType()
+ "; charset=\"" + message.getCharset() + "\""); + "; charset=\"" + message.getCharset() + "\"");

} else { } else {
mailMessage.setHeader("Content-Type", message.getMimeType()); mailMessage.setHeader("Content-Type", message.getMimeType());
} }
e = headers.elements();
while (e.hasMoreElements()) {
Header h = (Header) e.nextElement();
mailMessage.setHeader(h.getName(), h.getValue());
}
PrintStream out = mailMessage.getPrintStream(); PrintStream out = mailMessage.getPrintStream();
message.print(out); message.print(out);


e = files.elements(); e = files.elements();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
File file = (File) e.nextElement();

attach(file, out);
attach((File) e.nextElement(), out);
} }

mailMessage.sendAndClose(); mailMessage.sendAndClose();
} catch (IOException ioe) { } catch (IOException ioe) {
throw new BuildException("IO error sending mail", ioe); throw new BuildException("IO error sending mail", ioe);


Loading…
Cancel
Save