You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@turbine.apache.org by jv...@apache.org on 2001/07/10 02:39:39 UTC
cvs commit: jakarta-turbine/src/adapter/org/apache/turbine/util/mail ByteArrayDataSource.java Email.java EmailAttachment.java HtmlEmail.java MailMessage.java MultiPartEmail.java SimpleEmail.java
jvanzyl 01/07/09 17:39:39
Added: src/adapter/org/apache/turbine/util/mail
ByteArrayDataSource.java Email.java
EmailAttachment.java HtmlEmail.java
MailMessage.java MultiPartEmail.java
SimpleEmail.java
Log:
- adapter code
Revision Changes Path
1.1 jakarta-turbine/src/adapter/org/apache/turbine/util/mail/ByteArrayDataSource.java
Index: ByteArrayDataSource.java
===================================================================
package org.apache.turbine.util.mail;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 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 acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache Turbine" 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",
* "Apache Turbine", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* 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/>.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import javax.activation.DataSource;
/**
* This class implements a typed DataSource from:<br>
*
* - an InputStream<br>
* - a byte array<br>
* - a String<br>
*
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:bmclaugh@algx.net">Brett McLaughlin</a>
* @version $Id: ByteArrayDataSource.java,v 1.1 2001/07/10 00:39:39 jvanzyl Exp $
*/
public class ByteArrayDataSource
implements DataSource
{
/** Data. */
private byte[] data;
/** Content-type. */
private String type;
private ByteArrayOutputStream baos;
/**
* Create a datasource from a byte array.
*
* @param data A byte[].
* @param type A String.
*/
public ByteArrayDataSource(byte[] data,
String type)
{
this.data = data;
this.type = type;
}
/**
* Create a datasource from an input stream.
*
* @param is An InputStream.
* @param type A String.
*/
public ByteArrayDataSource(InputStream is,
String type)
{
this.type = type;
try
{
int ch;
ByteArrayOutputStream os = new ByteArrayOutputStream();
BufferedInputStream isReader = new BufferedInputStream( is );
BufferedOutputStream osWriter = new BufferedOutputStream( os );
while ((ch = isReader.read()) != -1)
{
osWriter.write(ch);
}
data = os.toByteArray();
}
catch (IOException ioex)
{
// Do something!
}
}
/**
* Create a datasource from a String.
*
* @param data A String.
* @param type A String.
*/
public ByteArrayDataSource(String data,
String type)
{
this.type = type;
try
{
// Assumption that the string contains only ASCII
// characters! Else just pass in a charset into this
// constructor and use it in getBytes().
this.data = data.getBytes("iso-8859-1");
}
catch (UnsupportedEncodingException uex)
{
// Do something!
}
}
/**
* Get the content type.
*
* @return A String.
*/
public String getContentType()
{
if ( type == null )
return "application/octet-stream";
else
return type;
}
/**
* Get the input stream.
*
* @return An InputStream.
* @exception IOException.
*/
public InputStream getInputStream()
throws IOException
{
if (data == null)
throw new IOException("no data");
return new ByteArrayInputStream(data);
}
/**
* Get the name.
*
* @return A String.
*/
public String getName()
{
return "ByteArrayDataSource";
}
/**
* Get the output stream.
*
* @return An OutputStream.
* @exception IOException.
*/
public OutputStream getOutputStream()
throws IOException
{
baos = new ByteArrayOutputStream();
return baos;
}
}
1.1 jakarta-turbine/src/adapter/org/apache/turbine/util/mail/Email.java
Index: Email.java
===================================================================
package org.apache.turbine.util.mail;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 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 acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache Turbine" 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",
* "Apache Turbine", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* 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/>.
*/
import java.util.Date;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
//!! these are bad.
import org.apache.turbine.services.resources.TurbineResources;
import org.apache.turbine.services.db.util.Criteria;
/**
* The base class for all email messages. This class sets the
* sender's email & name, receiver's email & name, subject, and the
* sent date. Subclasses are responsible for setting the message
* body.
*
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:frank.kim@clearink.com">Frank Y. Kim</a>
* @author <a href="mailto:bmclaugh@algx.net">Brett McLaughlin</a>
* @author <a href="mailto:greg@shwoop.com">Greg Ritter</a>
* @author <a href="mailto:unknown">Regis Koenig</a>
* @version $Id: Email.java,v 1.1 2001/07/10 00:39:39 jvanzyl Exp $
*/
public abstract class Email
{
/** Constants used to Email classes. */
public static final String SENDER_EMAIL = "sender.email";
public static final String SENDER_NAME = "sender.name";
public static final String RECEIVER_EMAIL = "receiver.email";
public static final String RECEIVER_NAME = "receiver.name";
public static final String EMAIL_SUBJECT = "email.subject";
public static final String EMAIL_BODY = "email.body";
public static final String CONTENT_TYPE = "content.type";
public static final String MAIL_SERVER = "mail.server";
public static final String MAIL_HOST = "mail.host";
public static final String MAIL_SMTP_FROM = "mail.smtp.from";
public static final String MAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol";
public static final String SMTP = "SMTP";
public static final String TEXT_HTML = "text/html";
public static final String TEXT_PLAIN = "text/plain";
public static final String ATTACHMENTS = "attachments";
public static final String FILE_SERVER = "file.server";
public static final String KOI8_R = "koi8-r";
public static final String ISO_8859_1 = "iso-8859-1";
public static final String US_ASCII = "us-ascii";
/** The email message to send. */
protected MimeMessage message;
/** The charset to use for this message */
protected String charset = null;
/** Lists of related email adresses */
private Vector toList;
private Vector ccList;
private Vector bccList;
private Vector replyList;
/**
* Set the charset of the message.
*
* @param charset A String.
* @return An HtmlEmail.
* @exception MessagingException.
*/
public void setCharset(String charset)
{
this.charset = charset;
}
/**
* TODO: Document.
*
* @return A Session.
*/
private Session getMailSession()
{
Properties properties = System.getProperties();
properties.put ( MAIL_TRANSPORT_PROTOCOL, SMTP );
properties.put ( MAIL_HOST,
TurbineResources.getString( MAIL_SERVER ) );
String mailSMTPFrom = TurbineResources.getString(MAIL_SMTP_FROM);
if(mailSMTPFrom!=null && !mailSMTPFrom.equals("")) {
properties.put ( MAIL_SMTP_FROM, mailSMTPFrom );
}
return Session.getDefaultInstance(properties, null);
}
/**
* Initializes the mail.
*
* Deprecated.
*
* @param criteria A Criteria.
* @exception MessagingException.
* @see #init() init.
*/
protected void initialize(Criteria criteria)
throws MessagingException
{
init();
initCriteria(criteria);
}
/**
* Initializes the mail.
*
* <p>This is the first method that should be called by a subclass
* in its constructor.
*
* @exception MessagingException.
*/
protected void init()
throws MessagingException
{
// Create the message.
message = new MimeMessage( getMailSession() );
toList = new Vector();
ccList = new Vector();
bccList = new Vector();
replyList = new Vector();
// Set the sent date.
setSentDate( new Date() );
}
/**
* Initialize the mail according to the Criteria.
*
* <p>This method uses the criteria parameter to set the from, to
* and subject fields of the email.
*
* Deprecated; one should use the setFrom, addTo, etc. methods.
*
* @param criteria A Criteria.
* @exception MessagingException.
*/
protected void initCriteria( Criteria criteria )
throws MessagingException
{
// Set the FROM field.
if( criteria.containsKey( SENDER_EMAIL) &&
criteria.containsKey( SENDER_NAME ) )
setFrom(criteria.getString( SENDER_EMAIL ),
criteria.getString( SENDER_NAME ));
// Set the TO field.
if( criteria.containsKey( RECEIVER_EMAIL) &&
criteria.containsKey( RECEIVER_NAME ) )
addTo( criteria.getString( RECEIVER_EMAIL ),
criteria.getString( RECEIVER_NAME ) );
// Set the SUBJECT field.
if( criteria.containsKey( EMAIL_SUBJECT ) )
setSubject( criteria.getString( EMAIL_SUBJECT ) );
else
setSubject( "no subject available" );
}
/**
* Set the FROM field of the email.
*
* @param email A String.
* @param name A String.
* @return An Email.
* @exception MessagingException.
*/
public Email setFrom(String email,
String name )
throws MessagingException
{
try
{
if ( name == null || name.trim().equals("") )
{
name = email;
}
message.setFrom(new InternetAddress( email, name ) );
}
catch( Exception e )
{
throw new MessagingException("cannot set from", e);
}
return this;
}
/**
* Add a recipient TO to the email.
*
* @param email A String.
* @param name A String.
* @return An Email.
* @exception MessagingException.
*/
public Email addTo(String email,
String name )
throws MessagingException
{
try
{
if ( name == null || name.trim().equals("") )
{
name = email;
}
toList.addElement( new InternetAddress( email, name ) );
}
catch( Exception e )
{
throw new MessagingException("cannot add to", e);
}
return this;
}
/**
* Add a recipient CC to the email.
*
* @param email A String.
* @param name A String.
* @return An Email.
* @exception MessagingException.
*/
public Email addCc(String email,
String name )
throws MessagingException
{
try
{
if ( name == null || name.trim().equals("") )
{
name = email;
}
ccList.addElement( new InternetAddress( email, name ) );
}
catch( Exception e )
{
throw new MessagingException("cannot add cc", e);
}
return this;
}
/**
* Add a blind BCC recipient to the email.
*
* @param email A String.
* @param name A String.
* @return An Email.
* @exception MessagingException.
*/
public Email addBcc(String email,
String name )
throws MessagingException
{
try
{
if ( name == null || name.trim().equals("") )
{
name = email;
}
bccList.addElement( new InternetAddress( email, name ) );
}
catch( Exception e )
{
throw new MessagingException("cannot add bcc", e);
}
return this;
}
/**
* Add a reply to address to the email.
*
* @param email A String.
* @param name A String.
* @return An Email.
* @exception MessagingException.
*/
public Email addReplyTo(String email,
String name )
throws MessagingException
{
try
{
if ( name == null || name.trim().equals("") )
{
name = email;
}
replyList.addElement( new InternetAddress( email, name ) );
}
catch( Exception e )
{
throw new MessagingException("cannot add replyTo", e);
}
return this;
}
/**
* Set the email subject.
*
* @param subject A String.
* @return An Email.
* @exception MessagingException.
*/
public Email setSubject( String subject )
throws MessagingException
{
if ( charset != null )
{
message.setSubject(subject, charset);
}
else
{
message.setSubject(subject);
}
return this;
}
/**
* Set the sent date field.
*
* @param date A Date.
* @return An Email.
* @exception MessagingException.
*/
public Email setSentDate( Date date )
throws MessagingException
{
message.setSentDate( date );
return this;
}
/**
* Define the content of the mail. It should be overidden by the
* subclasses.
*
* @param msg A String.
* @return An Email.
* @exception MessagingException.
*/
public abstract Email setMsg(String msg)
throws MessagingException;
/**
* Does the work of actually sending the email.
*
* @exception MessagingException, if there was an error.
*/
public void send()
throws MessagingException
{
InternetAddress[] foo = new InternetAddress[0];
message.setRecipients(Message.RecipientType.TO,
toInternetAddressArray(toList));
message.setRecipients(Message.RecipientType.CC,
toInternetAddressArray(ccList));
message.setRecipients(Message.RecipientType.BCC,
toInternetAddressArray(bccList));
message.setReplyTo(toInternetAddressArray(replyList));
Transport.send( message );
}
/**
* Utility to copy Vector of known InternetAddress objects into an
* array.
*
* @param v A Vector.
* @return An InternetAddress[].
*/
private InternetAddress[] toInternetAddressArray(Vector v)
{
int size = v.size();
InternetAddress[] ia = new InternetAddress[size];
for (int i=0; i<size; i++)
{
ia[i] = (InternetAddress)v.elementAt(i);
}
return ia;
}
}
1.1 jakarta-turbine/src/adapter/org/apache/turbine/util/mail/EmailAttachment.java
Index: EmailAttachment.java
===================================================================
package org.apache.turbine.util.mail;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 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 acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache Turbine" 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",
* "Apache Turbine", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* 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/>.
*/
import java.net.URL;
/**
* This class models an email attachment. Used by MultiPartEmail.
*
* @author <a href="mailto:frank.kim@clearink.com">Frank Y. Kim</a>
* @version $Id: EmailAttachment.java,v 1.1 2001/07/10 00:39:39 jvanzyl Exp $
*/
public class EmailAttachment
{
public final static String ATTACHMENT = javax.mail.Part.ATTACHMENT;
public final static String INLINE = javax.mail.Part.INLINE;
/** The name of this attachment. */
private String name = "";
/** The description of this attachment. */
private String description = "";
/** The full path to this attachment (ie c:/path/to/file.jpg). */
private String path = "";
/** The HttpURI where the file can be got. */
private URL url = null;
/** The disposition. */
private String disposition = ATTACHMENT;
/**
* Get the description.
*
* @return A String.
*/
public String getDescription()
{
return description;
}
/**
* Get the name.
*
* @return A String.
*/
public String getName()
{
return name;
}
/**
* Get the path.
*
* @return A String.
*/
public String getPath()
{
return path;
}
/**
* Get the URL.
*
* @return A URL.
*/
public URL getURL()
{
return url;
}
/**
* Get the disposition.
*
* @return A String.
*/
public String getDisposition()
{
return disposition;
}
/**
* Set the description.
*
* @param desc A String.
*/
public void setDescription(String desc)
{
this.description = desc;
}
/**
* Set the name.
*
* @param name A String.
*/
public void setName(String name)
{
this.name = name;
}
/**
* Set the path.
*
* @param path A String.
*/
public void setPath(String path)
{
this.path = path;
}
/**
* Set the URL.
*
* @param url A URL.
*/
public void setURL(URL url)
{
this.url = url;
}
/**
* Set the disposition.
*
* @param disposition A String.
*/
public void setDisposition(String disposition)
{
this.disposition = disposition;
}
}
1.1 jakarta-turbine/src/adapter/org/apache/turbine/util/mail/HtmlEmail.java
Index: HtmlEmail.java
===================================================================
package org.apache.turbine.util.mail;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 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 acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache Turbine" 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",
* "Apache Turbine", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* 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/>.
*/
import java.net.URL;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import org.apache.ecs.Document;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.Body;
import org.apache.ecs.html.Html;
import org.apache.ecs.html.PRE;
import org.apache.turbine.util.GenerateUniqueId;
import org.apache.turbine.util.StringUtils;
/**
* An HTML multipart email.
*
* <p>This class is used to send HTML formatted email. A text message
* can also be set for HTML unaware email clients, such as text-based
* email clients.
*
* <p>This class also inherits from MultiPartEmail, so it is easy to
* add attachents to the email.
*
* <p>To send an email in HTML, one should create a HtmlEmail, then
* use the setFrom, addTo, etc. methods. The HTML content can be set
* with the setHtmlMsg method. The alternate text content can be set
* with setTextMsg.
*
* <p>Either the text or HTML can be omitted, in which case the "main"
* part of the multipart becomes whichever is supplied rather than a
* multipart/alternative.
*
* @author <a href="mailto:unknown">Regis Koenig</a>
* @author <a href="mailto:sean@informage.net">Sean Legassick</a>
* @version $Id: HtmlEmail.java,v 1.1 2001/07/10 00:39:39 jvanzyl Exp $
*/
public class HtmlEmail
extends MultiPartEmail
{
protected MimeMultipart htmlContent;
protected String text;
protected String html;
/**
* Basic constructor.
*
* @exception MessagingException.
*/
public HtmlEmail()
throws MessagingException
{
this.init();
}
/**
* Instantiates a new MimeMultipart object if it isn't already
* instantiated.
*
* @return A MimeMultipart object
*/
public MimeMultipart getHtmlContent()
{
if (htmlContent == null)
{
htmlContent = new MimeMultipart();
}
return htmlContent;
}
/**
* Set the text content.
*
* @param text A String.
* @return An HtmlEmail.
* @exception MessagingException.
*/
public HtmlEmail setTextMsg(String text)
throws MessagingException
{
this.text = text;
return this;
}
/**
* Set the HTML content.
*
* @param html A String.
* @return An HtmlEmail.
* @exception MessagingException.
*/
public HtmlEmail setHtmlMsg(String html)
throws MessagingException
{
this.html = html;
return this;
}
/**
* Set the HTML content based on an ECS document.
*
* @param doc A Document.
* @return An HtmlEmail.
* @exception MessagingException.
*/
public HtmlEmail setHtmlMsg(Document doc)
throws MessagingException
{
return setHtmlMsg(doc.toString());
}
/**
* Set the message.
*
* <p>This method overrides the MultiPartEmail setMsg() method in
* order to send an HTML message instead of a full text message in
* the mail body. The message is formatted in HTML for the HTML
* part of the message, it is let as is in the alternate text
* part.
*
* @param msg A String.
* @return An Email.
* @exception MessagingException.
*/
public Email setMsg(String msg)
throws MessagingException
{
setTextMsg(msg);
setHtmlMsg(new ElementContainer(new Html(new Body()
.addElement(new PRE(msg)))).toString());
return this;
}
/**
* Embeds an URL in the HTML.
*
* <p>This method allows to embed a file located by an URL into
* the mail body. It allows, for instance, to add inline images
* to the email. Inline files may be referenced with a
* <code>cid:xxxxxx</code> URL, where xxxxxx is the Content-ID
* returned by the embed function.
*
* <p>Example of use:<br><code><pre>
* HtmlEmail he = new HtmlEmail();
* he.setHtmlMsg("<html><img src=cid:"+embed("file:/my/image.gif","image.gif")+"></html>");
* // code to set the others email fields (not shown)
* </pre></code>
*
* @param url The URL of the file.
* @param name The name that will be set in the filename header
* field.
* @return A String with the Content-ID of the file.
* @exception MessagingException.
*/
public String embed(URL url, String name)
throws MessagingException
{
MimeBodyPart mbp = new MimeBodyPart();
mbp.setDataHandler ( new DataHandler( new URLDataSource(url) ) );
mbp.setFileName( name );
mbp.setDisposition("inline");
String cid = org.apache.turbine.util.GenerateUniqueId.getIdentifier();
mbp.addHeader("Content-ID", cid);
getHtmlContent().addBodyPart( mbp );
return mbp.getContentID();
}
/**
* Does the work of actually sending the email.
*
* @exception MessagingException, if there was an error.
*/
public void send()
throws MessagingException
{
MimeBodyPart msgText = null;
MimeBodyPart msgHtml = null;
if (StringUtils.isValid(text) && StringUtils.isValid(html))
{
// The message in text and HTML form.
MimeMultipart msg = getHtmlContent();
msg.setSubType("alternative");
main.setContent(msg);
msgText = new MimeBodyPart();
msgHtml = new MimeBodyPart();
msg.addBodyPart(msgText);
msg.addBodyPart(msgHtml);
}
else if (StringUtils.isValid(text))
{
// just text so the text part is the main part
msgText = main;
}
else if (StringUtils.isValid(html))
{
// just HTML so the html part is the main part
msgHtml = main;
}
else
{
msgText = main;
text = "NO BODY";
}
if (msgText != null)
{
// add the text
if ( charset != null )
{
msgText.setText(text, charset);
}
else
{
msgText.setText(text);
}
}
if (msgHtml != null)
{
// add the html
if ( charset != null )
{
msgHtml.setContent( html, TEXT_HTML + ";charset=" + charset );
}
else
{
msgHtml.setContent( html, TEXT_HTML );
}
}
super.send();
}
}
1.1 jakarta-turbine/src/adapter/org/apache/turbine/util/mail/MailMessage.java
Index: MailMessage.java
===================================================================
package org.apache.turbine.util.mail;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 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 acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache Turbine" 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",
* "Apache Turbine", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* 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/>.
*/
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* Creates a very simple text/plain message and sends it.
*
* <p>MailMessage creates a very simple text/plain message and sends
* it. It can be used like this:<br>
* <pre>
* MailMessage sm = new MailMessage("mail.domain.net",
* "toYou@domain.net",
* "fromMe@domain",
* "this is the subject",
* "this is the body");
* </pre>
*
* Another example is:<br>
* <pre>
* MailMessage sm = new MailMessage();
* sm.setHost("mail.domain.net");
* sm.setHeaders("X-Mailer: Sendmail class, X-Priority: 1(Highest)");
* sm.setFrom("Net Freak1 user1@domain.com");
* sm.setReplyTo("Net Freak8 user8@domain.com");
* sm.setTo("Net Freak2 user2@domain.com, Net Freak3 user3@domain.com");
* sm.setCc("Net Freak4 user4@domain.com, Net Freak5 user5@domain.com");
* sm.setBcc("Net Freak6 user6@domain.com, Net Freak7 user7@domain.com");
* sm.setSubject("New Sendmail Test");
* sm.setBody("Test message from Sendmail class, more features to be added.
* Like multipart messages, html, binary files...");
* sm.setDebug(true);
* sm.send();
* </pre>
*
* @author <a href="mailto:david@i2a.com">David Duddleston</a>
* @version $Id: MailMessage.java,v 1.1 2001/07/10 00:39:39 jvanzyl Exp $
*/
public class MailMessage
{
/**
* The host name of the mail server to use.
*/
protected String host;
/**
* Used to specify the mail headers. Example:
*
* X-Mailer: Sendmail, X-Priority: 1(highest)
* or 2(high) 3(normal) 4(low) and 5(lowest)
* Disposition-Notification-To: returnR user@domain.net
*/
protected Hashtable headers;
/**
* The email address that the mail is being sent from.
*/
protected InternetAddress from;
/**
* The email address used for replies to this message.
*/
protected InternetAddress[] replyTo;
/**
* The email address or addresses that the email is being sent to.
*/
protected InternetAddress[] to;
/**
* The email address or addresses that the email is being
* carbon-copied to.
*/
protected InternetAddress[] cc;
/**
* The email address or addresses that the email is being
* blind-carbon-copied to.
*/
protected InternetAddress[] bcc;
/**
* The subject of the email message.
*/
protected String subject;
/**
* The body of the email message.
*/
protected String body;
/**
* Displays debug information when true.
*/
protected boolean debug;
/**
* Default constructor. Must use the setHost, setTo, and other
* set functions to properly send an email. <b>host</b>,
* <b>to</b>, <b>cc</b>, <b>bcc</b>, and <b>from</b> are set to
* null. <b>subject</b>, and <b>body</b> are set to empty
* strings. <b>debug</b> is set to false.
*/
public MailMessage()
{
this(null,null,null,null,null,"","",false);
}
/**
* Constructor used to specify <b>host</b>, <b>to</b>,
* <b>from</b>, <b>subject</b>, and <b>body</b>.
*
* @param h A String with the host.
* @param t A String with the TO.
* @param f A String with the FROM.
* @param s A String with the SUBJECT.
* @param b A String with the BODY.
*/
public MailMessage(String h,
String t,
String f,
String s,
String b)
{
this(h,t,null,null,f,s,b,false);
}
/**
* Constructor used to specify <b>host</b>, <b>to</b>, <b>cc</b>,
* <b>bcc</b>, <b>from</b>, <b>subject</b>, <b>body</b>, and
* <b>debug</b>.
*
* @param h A String with the host.
* @param t A String with the TO.
* @param c A String with the CC.
* @param bc A String with the BCC.
* @param f A String with the FROM.
* @param s A String with the SUBJECT.
* @param b A String with the BODY.
* @param d True if debugging is wanted.
*/
public MailMessage(String h,
String t,
String c,
String bc,
String f,
String s,
String b,
boolean d)
{
host = h;
to = (t == null?null:parseAddressField(t));
cc = (cc == null?null:parseAddressField(c));
bcc = (bc == null?null:parseAddressField(bc));
from = (f == null?null:parseInternetAddress(f));
subject = s;
body = b;
debug = d;
}
/**
* Adds a header (name, value) to the headers Hashtable.
*
* @param name A String with the name.
* @param value A String with the value.
*/
public void addHeader(String name,
String value)
{
if (headers == null)
{
headers = new Hashtable();
}
headers.put(name,value);
}
/**
* Parse an address field.
*
* @param str A String with the address.
* @return An InternetAddress[].
*/
public static InternetAddress[] parseAddressField(String str)
{
String[] addressList;
if (str.indexOf(",") != -1)
{
Vector v = new Vector();
StringTokenizer st = new StringTokenizer(str, ",", false);
while (st.hasMoreTokens())
{
v.addElement(st.nextToken());
}
addressList = new String[v.size()];
for (int i = 0; i < v.size(); i++)
{
addressList[i] = (String)v.elementAt(i);
}
}
else
{
addressList = new String[1];
addressList[0] = str;
}
return parseAddressList(addressList);
}
/**
* Parse an address list.
*
* @param aList A String[] with the addresses.
* @return An InternetAddress[].
*/
public static InternetAddress[] parseAddressList(String[] aList)
{
InternetAddress[] ia = new InternetAddress[aList.length];
for (int i = 0; i < aList.length; i++)
{
ia[i] = parseInternetAddress(aList[i]);
}
return ia;
}
/**
* Parse a header.
*
* @param str A String with the header.
* @param headers A Hashtable with the current headers.
*/
public static void parseHeader(String str,
Hashtable headers)
{
String name = null;
String value = null;
str = str.trim();
int sp = str.lastIndexOf(":");
name = str.substring(0, sp);
value = (str.substring(sp+1)).trim();
headers.put(name, value);
}
/**
* Parse a header field.
*
* @param str A String with the header field.
* @return A Hashtable with the parsed headers.
*/
public static Hashtable parseHeaderField(String str)
{
String[] headerList;
if (str.indexOf(",") != -1)
{
Vector v = new Vector();
StringTokenizer st = new StringTokenizer(str, ",", false);
while( st.hasMoreTokens() )
{
v.addElement(st.nextToken());
}
headerList = new String[v.size()];
for (int i = 0; i < v.size(); i++)
{
headerList[i] = (String)v.elementAt(i);
}
}
else
{
headerList = new String[1];
headerList[0] = str;
}
return parseHeaderList(headerList);
}
/**
* Parse a header list.
*
* @param hList A String[] with the headers.
* @return A Hashtable with the parsed headers.
*/
public static Hashtable parseHeaderList(String[] hList)
{
Hashtable headers = new Hashtable();
for (int i = 0; i < hList.length; i++)
{
// headers.put("one", new Integer(1));
parseHeader(hList[i], headers);
}
return headers;
}
/**
* Parse an Internet address.
*
* @param str A String with the address.
* @return An InternetAddress.
*/
public static InternetAddress parseInternetAddress(String str)
{
String address = null;
String personal = null;
str = str.trim();
if (str.indexOf(" ") == -1)
{
address = str;
}
else
{
int sp = str.lastIndexOf(" ");
address = str.substring(sp+1);
personal = str.substring(0, sp);
}
return parseInternetAddress(address, personal);
}
/**
* Parse an Internet address.
*
* @param address A String with the address.
* @param personal A String.
* @return An InternetAddress.
*/
public static InternetAddress parseInternetAddress(String address,
String personal)
{
InternetAddress ia = null;
try
{
ia = new InternetAddress(address);
if (personal != null)
{
ia.setPersonal(personal);
}
}
catch (AddressException e)
{
e.printStackTrace();
System.out.println();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
System.out.println();
}
return ia;
}
/**
* Send the message. The to, from, subject, host, and body should
* be set prior to using this method.
*
* @return True is message was sent.
*/
public boolean send()
{
// Create some properties and get the default Session.
Properties props = new Properties();
props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
session.setDebug(debug);
try
{
// Create a message.
Message msg = new MimeMessage(session);
// Set the email address that the message is from.
msg.setFrom(from);
// Set the email addresses that the message is to.
msg.setRecipients(Message.RecipientType.TO, to);
// Set the email addresses that will be carbon-copied.
if (cc != null)
{
msg.setRecipients(Message.RecipientType.CC, cc);
}
// Set the email addresses that will be
// blind-carbon-copied.
if (bcc != null)
{
msg.setRecipients(Message.RecipientType.BCC, bcc);
}
// Set the email addresses that reply-to messages are
// sent.
if (replyTo != null)
{
msg.setReplyTo(replyTo);
}
// Set the subject of the email message.
msg.setSubject(subject);
// Set the body of the message. If the desired charset is
// known, use setText(text, charset).
msg.setText(body);
// msg.addHeader("X-Mailer", "com.i2a.util.mail.Sendmail");
if (headers != null)
{
Enumeration e = headers.keys();
while (e.hasMoreElements())
{
String name = (String)e.nextElement();
String value = (String)headers.get(name);
msg.addHeader(name, value);
}
}
// Send the message.
Transport.send(msg);
}
catch (MessagingException mex)
{
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null)
{
ex.printStackTrace();
}
return false;
}
return true;
}
/**
* Used to specify the email address that the mail is being
* blind-carbon-copied to.
*
* @param bc An InternetAddress[].
*/
public void setBcc(InternetAddress[] bc)
{
bcc = bc;
}
/**
* Used to specify the email address that the mail is being
* blind-carbon-copied to.
*
* @param bc A String.
*/
public void setBcc(String bc)
{
bcc = parseAddressField(bc);
}
/**
* Used to specify the body of the email message.
*
* @param b A String.
*/
public void setBody(String b)
{
body = b;
}
/**
* Used to specify the email address that the mail is being sent
* to.
*
* @param c An InternetAddress[].
*/
public void setCc(InternetAddress[] c)
{
cc = c;
}
/**
* Used to specify the email address that the mail is being
* carbon-copied to.
*
* @param c A String.
*/
public void setCc(String c)
{
cc = parseAddressField(c);
}
/**
* Setting to true will enable the display of debug information.
*
* @param str A String.
*/
public void setDebug(String str)
{
if (str.equals("1"))
{
debug = true;
}
else if (str.equals("0"))
{
debug = false;
}
else
{
debug = new Boolean(str).booleanValue();
}
}
/**
* Setting to true will enable the display of debug information.
*
* @param d A boolean.
*/
public void setDebug(boolean d)
{
debug = d;
}
/**
* Used to specify the email address that the mail is being sent
* from.
*
* @param f A String.
*/
public void setFrom(String f)
{
from = parseInternetAddress(f);
}
/**
* Used to specify the email address that the mail is being sent
* from.
*
* @param f An InternetAddress.
*/
public void setFrom(InternetAddress f)
{
from = f;
}
/**
* Used to specify the mail headers. Example:
*
* X-Mailer: Sendmail, X-Priority: 1(highest)
* or 2(high) 3(normal) 4(low) and 5(lowest)
* Disposition-Notification-To: returnR user@domain.net
*
* @param h A String.
*/
public void setHeaders(String h)
{
headers = parseHeaderField(h);
}
/**
* Used to specify the mail headers. Example:
*
* X-Mailer: Sendmail, X-Priority: 1(highest)
* or 2(high) 3(normal) 4(low) and 5(lowest)
* Disposition-Notification-To: returnR user@domain.net
*
* @param h A Hashtable.
*/
public void setHeaders(Hashtable h)
{
headers = h;
}
/**
* Used to specify the mail server host.
*
* @param h A String.
*/
public void setHost(String h)
{
host = h;
}
/**
* Used to specify the email address that the mail is being sent
* from.
*
* @param rt An InternetAddress[].
*/
public void setReplyTo(InternetAddress[] rt)
{
replyTo = rt;
}
/**
* Used to specify the email address that the mail is being sent
* from.
*
* @param rp A String.
*/
public void setReplyTo(String rp)
{
replyTo = parseAddressField(rp);
}
/**
* Used to specify the subject of the email message.
*
* @param s A String.
*/
public void setSubject(String s)
{
subject = s;
}
/**
* Used to specify the email address that the mail is being sent
* to.
*
* @param t An InternetAddress[].
*/
public void setTo(InternetAddress[] t)
{
to = t;
}
/**
* Used to specify the email address that the mail is being sent
* to.
*
* @param t A String.
*/
public void setTo(String t)
{
to = parseAddressField(t);
}
}
1.1 jakarta-turbine/src/adapter/org/apache/turbine/util/mail/MultiPartEmail.java
Index: MultiPartEmail.java
===================================================================
package org.apache.turbine.util.mail;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 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 acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache Turbine" 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",
* "Apache Turbine", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* 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/>.
*/
import java.net.URL;
import java.util.Hashtable;
import java.util.Vector;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.turbine.services.db.util.Criteria;
/**
* A multipart email.
*
* <p>This class is used to send multi-part internet email like
* messages with attachments.
*
* <p>To create a multi-part email, call the default constructor and
* then you can call setMsg() to set the message and call the
* different attach() methods.
*
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:frank.kim@clearink.com">Frank Y. Kim</a>
* @author <a href="mailto:bmclaugh@algx.net">Brett McLaughlin</a>
* @author <a href="mailto:unknown">Regis Koenig</a>
* @version $Id: MultiPartEmail.java,v 1.1 2001/07/10 00:39:39 jvanzyl Exp $
*/
public class MultiPartEmail
extends Email
{
/** Body portion of the email. */
protected MimeMultipart emailBody;
/** The message container. */
protected MimeBodyPart main;
/** The file server if it exists. */
private String fileServer = null;
/**
* Initialize the multipart email.
*
* @exception MessagingException.
*/
public MultiPartEmail()
throws MessagingException
{
this.init();
}
/**
* Constructor used to initialize attributes.
*
* <p>This method uses the criteria object to set the different
* fields of the e-mail. The expected fields of the Criteria are:
*
* <ul>
* <li>SENDER_EMAIL</li>
* <li>RECEIVER_EMAIL</li>
* <li>EMAIL_SUBJECT</li>
* <li>EMAIL_BODY</li>
* <li>ATTACHMENTS - A Vector of EmailAttachment.</li>
* <li>FILE_SERVER - Where the files are located. If not given,
* they are assumed to be local.</li>
* </ul>
*
* Deprecated, since Criteria is deprecated in mail API.
*
* @param criteria A Criteria.
* @exception MessagingException.
*/
public MultiPartEmail( Criteria criteria )
throws MessagingException
{
this.init();
this.initCriteria(criteria);
}
/**
* Initialize the multipart email.
*
* @exception MessagingException.
*/
protected void init()
throws MessagingException
{
super.init();
fileServer = null;
/* The body of the mail. */
emailBody = new MimeMultipart();
message.setContent( emailBody );
/* The main message content. */
main = new MimeBodyPart();
emailBody.addBodyPart(main);
}
/**
* Uses the criteria to set the fields.
*
* <p>This method uses the criteria object to set the different
* fields of the e-mail. The expected fields of the Criteria are:
*
* <ul>
* <li>SENDER_EMAIL</li>
* <li>RECEIVER_EMAIL</li>
* <li>EMAIL_SUBJECT</li>
* <li>EMAIL_BODY</li>
* <li>ATTACHMENTS - A Vector of EmailAttachment.</li>
* <li>FILE_SERVER - Where the files are located. If not given,
* they are assumed to be local.</li>
* </ul>
*
* Deprecated, since the Criteria is deprecated.
*
* @param criteria A Criteria.
* @exception MessagingException.
*/
protected void initCriteria( Criteria criteria )
throws MessagingException
{
super.initCriteria(criteria);
if( criteria.containsKey( EMAIL_BODY ) )
setMsg( criteria.getString( EMAIL_BODY ) );
else
setMsg("NO MESSAGE");
Vector attachments;
if( criteria.containsKey(ATTACHMENTS ) )
attachments = (Vector)criteria.get( ATTACHMENTS );
else
attachments = new Vector();
if( criteria.containsKey(FILE_SERVER) )
fileServer = criteria.getString(FILE_SERVER);
for (int i=0; i<attachments.size(); i++)
{
EmailAttachment attachment =
(EmailAttachment)attachments.elementAt(i);
attach( attachment );
}
}
/**
* Set the message of the email.
*
* @param msg A String.
* @return An Email.
* @exception MessagingException.
*/
public Email setMsg(String msg)
throws MessagingException
{
if ( charset != null )
{
main.setText(msg, charset);
}
else
{
main.setText(msg);
}
return this;
}
/**
* Attach an EmailAttachement.
*
* @param attachment An EmailAttachment.
* @return A MultiPartEmail.
* @exception MessagingException.
*/
public MultiPartEmail attach( EmailAttachment attachment )
throws MessagingException
{
URL url = attachment.getURL();
if( url == null )
{
try
{
String file = attachment.getPath();
url = new URL( "file", fileServer, file );
}
catch( Exception e)
{
throw new MessagingException("Cannot find file", e);
}
}
return attach(url,
attachment.getName(),
attachment.getDescription(),
attachment.getDisposition() );
}
/**
* Attach a file located by its URL. The disposition of the file
* is set to mixed.
*
* @param url The URL of the file (may be any valid URL).
* @param name The name field for the attachment.
* @param description A description for the attachment.
* @return A MultiPartEmail.
* @exception MessagingException.
*/
public MultiPartEmail attach( URL url,
String name,
String description )
throws MessagingException
{
return attach( url, name, description, EmailAttachment.ATTACHMENT);
}
/**
* Attach a file located by its URL.
*
* @param url The URL of the file (may be any valid URL).
* @param name The name field for the attachment.
* @param description A description for the attachment.
* @param disposition Either mixed or inline.
* @return A MultiPartEmail.
* @exception MessagingException.
*/
public MultiPartEmail attach( URL url,
String name,
String description,
String disposition)
throws MessagingException
{
return attach( new URLDataSource(url), name, description, disposition );
}
/**
* Attach a file specified as a DataSource interface.
*
* @param ds A DataSource interface for the file.
* @param name The name field for the attachment.
* @param description A description for the attachment.
* @return A MultiPartEmail.
* @exception MessagingException.
*/
public MultiPartEmail attach( DataSource ds,
String name,
String description)
throws MessagingException
{
return attach ( ds, name, description, EmailAttachment.ATTACHMENT);
}
/**
* Attach a file specified as a DataSource interface.
*
* @param ds A DataSource interface for the file.
* @param name The name field for the attachment.
* @param description A description for the attachement.
* @param disposition Either mixed or inline.
* @return A MultiPartEmail.
* @exception MessagingException.
*/
public MultiPartEmail attach( DataSource ds,
String name,
String description,
String disposition)
throws MessagingException
{
MimeBodyPart mbp = new MimeBodyPart();
emailBody.addBodyPart( mbp );
mbp.setDisposition( disposition );
mbp.setFileName ( name );
mbp.setDescription ( description );
mbp.setDataHandler ( new DataHandler( ds ) );
return this;
}
}
1.1 jakarta-turbine/src/adapter/org/apache/turbine/util/mail/SimpleEmail.java
Index: SimpleEmail.java
===================================================================
package org.apache.turbine.util.mail;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 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 acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache Turbine" 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",
* "Apache Turbine", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* 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/>.
*/
import java.util.Hashtable;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.turbine.services.db.util.Criteria;
/**
* This class is used to send simple internet email messages without
* attachments.
*
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:frank.kim@clearink.com">Frank Y. Kim</a>
* @author <a href="mailto:bmclaugh@algx.net">Brett McLaughlin</a>
* @author <a href="mailto:unknown">Regis Koenig</a>
* @version $Id: SimpleEmail.java,v 1.1 2001/07/10 00:39:39 jvanzyl Exp $
*/
public class SimpleEmail
extends Email
{
/** the conentet type for body of the message */
private String contentType = null;
/**
* Default constructor.
*
* @exception MessagingException.
*/
public SimpleEmail()
throws MessagingException
{
super.init();
}
/**
* Constructor used to initialize attributes. To create a simple
* email you need to pass a Criteria object into the SimpleEmail
* constructor which contains:
*
* <ul>
* <li>SENDER_EMAIL</li>
* <li>SENDER_NAME</li>
* <li>RECEIVER_EMAIL</li>
* <li>RECEIVER_NAME</li>
* <li>EMAIL_SUBJECT</li>
* <li>EMAIL_BODY</li>
* </ul>
*
* Deprecated, since Criteria is deprecated in mail API.
*
* @param criteria A Criteria.
* @exception MessagingException.
*/
public SimpleEmail( Criteria criteria )
throws MessagingException
{
super.init();
this.initCriteria(criteria);
}
/**
* Uses the criteria to set the fields.
*
* Deprecated, since the Criteria is deprecated.
*
* @param criteria A Criteria.
* @exception MessagingException.
*/
protected void initCriteria( Criteria criteria )
throws MessagingException
{
super.initCriteria(criteria);
if( criteria.containsKey( CONTENT_TYPE ) )
contentType = criteria.getString( CONTENT_TYPE );
if( criteria.containsKey( EMAIL_BODY ) )
setMsg( criteria.getString( EMAIL_BODY ) );
else
setMsg("NO MESSAGE");
}
/**
* Set the content of the mail
*
* @param msg A String.
* @return An Email.
* @exception MessagingException.
*/
public Email setMsg( String msg )
throws MessagingException
{
if (contentType == null)
contentType = TEXT_PLAIN;
message.setContent( msg, contentType );
return this;
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: turbine-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: turbine-dev-help@jakarta.apache.org