/*
* Copyright (C) 2006 Methodhead Software LLC. All rights reserved.
*
* This file is part of TransferCM.
*
* TransferCM is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* TransferCM is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* TransferCM; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.methodhead.mail;
import java.io.File;
import java.util.Properties;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
import org.apache.commons.mail.SimpleEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.EmailAttachment;
import com.methodhead.MhfException;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* Provides simplified interface for sending email messages. This class uses
* the Jakarta Commons Email API to send messages.
*/
public class Mail {
// constructors /////////////////////////////////////////////////////////////
// constants ////////////////////////////////////////////////////////////////
// classes //////////////////////////////////////////////////////////////////
// methods //////////////////////////////////////////////////////////////////
/**
* <p>
* Sets the properties that contain configuration parameters.
* JavaMail is used to send mail, and these properties are
* passed directly to JavaMail classes. The following
* properties (and their default values) are important:
* </p>
* <ul>
* <li>mail.host (The local machine)</li>
* <li>mail.from (<tt>username@host</tt>)</li>
* </ul>
* <p>
* Find information about all setting in Appendix A of the
* JavaMail API Design Specification.
* </p>
*/
public static void init(
Properties props ) {
if ( logger_.isDebugEnabled() ) {
logger_.debug(
"Initializing with properties " +
new ToStringBuilder( props ).
append( "mail.host", props.get( "mail.host" ) ).
append( "mail.from", props.get( "mail.from" ) ).
toString() );
}
mailProperties_ = props;
}
/**
* Instantiates and initializes a new <tt>SimpleEmail</tt> (not unit tested).
*/
public static SimpleEmail newSimpleEmail() {
SimpleEmail email = new SimpleEmail();
email.setHostName( mailProperties_.getProperty( "mail.host" ) );
return email;
}
/**
* Instantiates and initializes a new <tt>MultiPartEmail</tt> (not unit
* tested).
*/
public static MultiPartEmail newMultiPartEmail() {
MultiPartEmail email = new MultiPartEmail();
email.setHostName( mailProperties_.getProperty( "mail.host" ) );
return email;
}
/**
* Instantiates and initializes a new <tt>HtmlEmail</tt> (not unit tested).
*/
public static HtmlEmail newHtmlEmail() {
HtmlEmail email = new HtmlEmail();
email.setHostName( mailProperties_.getProperty( "mail.host" ) );
return email;
}
/**
* Utility method to validate an email address.
*/
protected static boolean isValidAddress(
String address ) {
if ( address == null )
return false;
try {
InternetAddress ia = new InternetAddress( address );
ia.validate();
}
catch ( AddressException e ) {
return false;
}
return true;
}
/**
* Sends <tt>text</tt> with <tt>subject</tt> to each email address in
* <tt>to</tt>. Any invalid email addresses in <tt>to</tt> are ignored, but
* an invalid <tt>from</tt> address will throw an exception.
* <strong>Note:</strong> Each message is sent individually; be aware of the
* load on your mail server.
*/
public static void send(
String[] to,
String from,
String subject,
String text ) {
if ( logger_.isDebugEnabled() ) {
logger_.debug( "Sending plain text email from " + from + " with subject \"" + subject + "\", " + text.length() + " characters in body." );
}
try {
for ( int i = 0; i < to.length; i++ ) {
if ( isValidAddress( to[ i ] ) ) {
if ( logger_.isDebugEnabled() ) {
logger_.debug( "Sending message to " + to[ i ] );
}
SimpleEmail email = newSimpleEmail();
email.addTo( to[ i ] );
email.setFrom( from );
email.setSubject( subject );
email.setMsg( text );
email.send();
}
else {
if ( logger_.isDebugEnabled() ) {
logger_.debug( "Skipping invalid email address " + to[ i ] );
}
}
}
}
catch ( EmailException e ) {
String msg =
"Sending plain text email from " + from + " with subject \"" + subject + "\", " + text.length() + " characters in body.\n" +
ExceptionUtils.getStackTrace( e );
logger_.error( msg );
throw new MhfException( msg );
}
}
/**
* Sends <tt>text</tt> with <tt>subject</tt> to <tt>to</tt>. If <tt>to</tt>
* is invalid, no email is sent, but an invalid <tt>from</tt> address will
* throw an exception.
*/
public static void send(
String to,
String from,
String subject,
String text )
throws
EmailException {
send( new String[] { to }, from, subject, text );
}
/**
* Sends <tt>text</tt> and <tt>html</tt> with <tt>subject</tt> to each email
* address in <tt>to</tt>. Any invalid email addresses in <tt>to</tt> are
* ignored, but an invalid <tt>from</tt> address will throw an
* exception. <strong>Note:</strong> Each message is sent
* individually; be aware of the load on your mail server.
*/
public static void send(
String[] to,
String from,
String subject,
String text,
String html ) {
send( to, from, subject, text, html, new File[] {} );
}
/**
* Sends <tt>text</tt> with <tt>subject</tt> and <tt>attachments</tt> to each
* email address in <tt>to</tt>. Any invalid email addresses in <tt>to</tt>
* are ignored, but an invalid <tt>from</tt> address will throw an
* exception. A null or non-existant file in attachments
* will throw a <tt>MessagingException</tt>. <strong>Note:</strong> Each
* message is sent individually; be aware of the load on your mail server.
*/
public static void send(
String[] to,
String from,
String subject,
String text,
File[] attachments ) {
send( to, from, subject, text, null, attachments );
}
/**
* Sends <tt>text</tt> and <tt>html</tt> with <tt>subject</tt> and
* <tt>attachments</tt> to each email address in <tt>to</tt>. If
* <tt>html</tt> is <tt>null</tt>, a text-only email is sent. Any invalid
* email addresses in <tt>to</tt> are ignored, but an invalid <tt>from</tt>
* address will throw an exception. A null or non-existant
* file in attachments will throw a <tt>MessagingException</tt>.
* <strong>Note:</strong> Each message is sent individually; be aware of the
* load on your mail server.
*/
public static void send(
String[] to,
String from,
String subject,
String text,
String html,
File[] attachments ) {
if ( logger_.isDebugEnabled() ) {
String textInfo = "no text";
if ( text != null ) {
textInfo = "" + text.length() + " characters in text body";
}
String htmlInfo = "no html";
if ( html != null ) {
htmlInfo = "" + html.length() + " characters in html body";
}
logger_.debug(
"Sending html email from " + from + " with subject \"" + subject + "\", " + textInfo + ", " +
htmlInfo + ", and attachments " + StringUtils.join( attachments ) );
}
try {
if ( attachments == null )
throw new EmailException( "Attachments array is null." );
//
// create EmailAttachments
//
EmailAttachment[] emailAttachments =
new EmailAttachment[ attachments.length ];
for ( int i = 0; i < attachments.length; i++ ) {
//
// valid attachment?
//
if (
( attachments[ i ] == null ) ||
!attachments[ i ].exists() ||
!attachments[ i ].isFile() )
throw new EmailException(
"Attachment \"" + attachments[ i ] +
"\" does not exist or is not a file." );
emailAttachments[ i ] = new EmailAttachment();
emailAttachments[ i ].setPath( attachments[ i ].getAbsolutePath() );
}
for ( int i = 0; i < to.length; i++ ) {
if ( isValidAddress( to[ i ] ) ) {
if ( logger_.isDebugEnabled() ) {
logger_.debug( "Sending to " + to[ i ] );
}
HtmlEmail email = newHtmlEmail();
email.addTo( to[ i ] );
email.setFrom( from );
email.setSubject( subject );
if ( text != null )
email.setTextMsg( text );
if ( html != null )
email.setHtmlMsg( html );
//
// add attachments
//
for ( int j = 0; j < emailAttachments.length; j++ )
email.attach( emailAttachments[ j ] );
email.send();
}
else {
if ( logger_.isDebugEnabled() ) {
logger_.debug( "Skipping invalid email address " + to[ i ] );
}
}
}
}
catch ( EmailException e ) {
String msg =
"Sending html email from " + from + " to " + to +
" with subject \"" + subject + "\", text \"" + text + "\", html \"" +
html + "\", and attachments " + attachments + "\n" +
ExceptionUtils.getStackTrace( e );
logger_.error( msg );
throw new MhfException( msg );
}
}
// properties ///////////////////////////////////////////////////////////////
// attributes ///////////////////////////////////////////////////////////////
protected static Properties mailProperties_ = new Properties();
private static Logger logger_ = Logger.getLogger( Mail.class );
}
|