001: /*
002: * Copyright (C) 2006 Methodhead Software LLC. All rights reserved.
003: *
004: * This file is part of TransferCM.
005: *
006: * TransferCM is free software; you can redistribute it and/or modify it under the
007: * terms of the GNU General Public License as published by the Free Software
008: * Foundation; either version 2 of the License, or (at your option) any later
009: * version.
010: *
011: * TransferCM is distributed in the hope that it will be useful, but WITHOUT ANY
012: * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
013: * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
014: * details.
015: *
016: * You should have received a copy of the GNU General Public License along with
017: * TransferCM; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
018: * Fifth Floor, Boston, MA 02110-1301 USA
019: */
020:
021: package com.methodhead.mail;
022:
023: import java.io.File;
024: import java.util.Properties;
025: import javax.mail.internet.InternetAddress;
026: import javax.mail.internet.AddressException;
027: import org.apache.commons.mail.SimpleEmail;
028: import org.apache.commons.mail.MultiPartEmail;
029: import org.apache.commons.mail.HtmlEmail;
030: import org.apache.commons.mail.EmailException;
031: import org.apache.commons.mail.EmailAttachment;
032: import com.methodhead.MhfException;
033: import org.apache.commons.lang.exception.ExceptionUtils;
034: import org.apache.commons.lang.builder.ToStringBuilder;
035: import org.apache.commons.lang.StringUtils;
036: import org.apache.log4j.Logger;
037:
038: /**
039: * Provides simplified interface for sending email messages. This class uses
040: * the Jakarta Commons Email API to send messages.
041: */
042: public class Mail {
043:
044: // constructors /////////////////////////////////////////////////////////////
045:
046: // constants ////////////////////////////////////////////////////////////////
047:
048: // classes //////////////////////////////////////////////////////////////////
049:
050: // methods //////////////////////////////////////////////////////////////////
051:
052: /**
053: * <p>
054: * Sets the properties that contain configuration parameters.
055: * JavaMail is used to send mail, and these properties are
056: * passed directly to JavaMail classes. The following
057: * properties (and their default values) are important:
058: * </p>
059: * <ul>
060: * <li>mail.host (The local machine)</li>
061: * <li>mail.from (<tt>username@host</tt>)</li>
062: * </ul>
063: * <p>
064: * Find information about all setting in Appendix A of the
065: * JavaMail API Design Specification.
066: * </p>
067: */
068: public static void init(Properties props) {
069:
070: if (logger_.isDebugEnabled()) {
071: logger_.debug("Initializing with properties "
072: + new ToStringBuilder(props).append("mail.host",
073: props.get("mail.host")).append("mail.from",
074: props.get("mail.from")).toString());
075: }
076:
077: mailProperties_ = props;
078: }
079:
080: /**
081: * Instantiates and initializes a new <tt>SimpleEmail</tt> (not unit tested).
082: */
083: public static SimpleEmail newSimpleEmail() {
084:
085: SimpleEmail email = new SimpleEmail();
086: email.setHostName(mailProperties_.getProperty("mail.host"));
087: return email;
088: }
089:
090: /**
091: * Instantiates and initializes a new <tt>MultiPartEmail</tt> (not unit
092: * tested).
093: */
094: public static MultiPartEmail newMultiPartEmail() {
095:
096: MultiPartEmail email = new MultiPartEmail();
097: email.setHostName(mailProperties_.getProperty("mail.host"));
098: return email;
099: }
100:
101: /**
102: * Instantiates and initializes a new <tt>HtmlEmail</tt> (not unit tested).
103: */
104: public static HtmlEmail newHtmlEmail() {
105:
106: HtmlEmail email = new HtmlEmail();
107: email.setHostName(mailProperties_.getProperty("mail.host"));
108: return email;
109: }
110:
111: /**
112: * Utility method to validate an email address.
113: */
114: protected static boolean isValidAddress(String address) {
115:
116: if (address == null)
117: return false;
118:
119: try {
120: InternetAddress ia = new InternetAddress(address);
121: ia.validate();
122: } catch (AddressException e) {
123: return false;
124: }
125:
126: return true;
127: }
128:
129: /**
130: * Sends <tt>text</tt> with <tt>subject</tt> to each email address in
131: * <tt>to</tt>. Any invalid email addresses in <tt>to</tt> are ignored, but
132: * an invalid <tt>from</tt> address will throw an exception.
133: * <strong>Note:</strong> Each message is sent individually; be aware of the
134: * load on your mail server.
135: */
136: public static void send(String[] to, String from, String subject,
137: String text) {
138:
139: if (logger_.isDebugEnabled()) {
140: logger_.debug("Sending plain text email from " + from
141: + " with subject \"" + subject + "\", "
142: + text.length() + " characters in body.");
143: }
144:
145: try {
146: for (int i = 0; i < to.length; i++) {
147: if (isValidAddress(to[i])) {
148:
149: if (logger_.isDebugEnabled()) {
150: logger_.debug("Sending message to " + to[i]);
151: }
152:
153: SimpleEmail email = newSimpleEmail();
154: email.addTo(to[i]);
155: email.setFrom(from);
156: email.setSubject(subject);
157: email.setMsg(text);
158: email.send();
159: } else {
160: if (logger_.isDebugEnabled()) {
161: logger_.debug("Skipping invalid email address "
162: + to[i]);
163: }
164: }
165: }
166: } catch (EmailException e) {
167: String msg = "Sending plain text email from " + from
168: + " with subject \"" + subject + "\", "
169: + text.length() + " characters in body.\n"
170: + ExceptionUtils.getStackTrace(e);
171: logger_.error(msg);
172: throw new MhfException(msg);
173: }
174: }
175:
176: /**
177: * Sends <tt>text</tt> with <tt>subject</tt> to <tt>to</tt>. If <tt>to</tt>
178: * is invalid, no email is sent, but an invalid <tt>from</tt> address will
179: * throw an exception.
180: */
181: public static void send(String to, String from, String subject,
182: String text) throws EmailException {
183:
184: send(new String[] { to }, from, subject, text);
185: }
186:
187: /**
188: * Sends <tt>text</tt> and <tt>html</tt> with <tt>subject</tt> to each email
189: * address in <tt>to</tt>. Any invalid email addresses in <tt>to</tt> are
190: * ignored, but an invalid <tt>from</tt> address will throw an
191: * exception. <strong>Note:</strong> Each message is sent
192: * individually; be aware of the load on your mail server.
193: */
194: public static void send(String[] to, String from, String subject,
195: String text, String html) {
196:
197: send(to, from, subject, text, html, new File[] {});
198: }
199:
200: /**
201: * Sends <tt>text</tt> with <tt>subject</tt> and <tt>attachments</tt> to each
202: * email address in <tt>to</tt>. Any invalid email addresses in <tt>to</tt>
203: * are ignored, but an invalid <tt>from</tt> address will throw an
204: * exception. A null or non-existant file in attachments
205: * will throw a <tt>MessagingException</tt>. <strong>Note:</strong> Each
206: * message is sent individually; be aware of the load on your mail server.
207: */
208: public static void send(String[] to, String from, String subject,
209: String text, File[] attachments) {
210:
211: send(to, from, subject, text, null, attachments);
212: }
213:
214: /**
215: * Sends <tt>text</tt> and <tt>html</tt> with <tt>subject</tt> and
216: * <tt>attachments</tt> to each email address in <tt>to</tt>. If
217: * <tt>html</tt> is <tt>null</tt>, a text-only email is sent. Any invalid
218: * email addresses in <tt>to</tt> are ignored, but an invalid <tt>from</tt>
219: * address will throw an exception. A null or non-existant
220: * file in attachments will throw a <tt>MessagingException</tt>.
221: * <strong>Note:</strong> Each message is sent individually; be aware of the
222: * load on your mail server.
223: */
224: public static void send(String[] to, String from, String subject,
225: String text, String html, File[] attachments) {
226:
227: if (logger_.isDebugEnabled()) {
228: String textInfo = "no text";
229: if (text != null) {
230: textInfo = "" + text.length()
231: + " characters in text body";
232: }
233:
234: String htmlInfo = "no html";
235: if (html != null) {
236: htmlInfo = "" + html.length()
237: + " characters in html body";
238: }
239:
240: logger_.debug("Sending html email from " + from
241: + " with subject \"" + subject + "\", " + textInfo
242: + ", " + htmlInfo + ", and attachments "
243: + StringUtils.join(attachments));
244: }
245:
246: try {
247: if (attachments == null)
248: throw new EmailException("Attachments array is null.");
249:
250: //
251: // create EmailAttachments
252: //
253: EmailAttachment[] emailAttachments = new EmailAttachment[attachments.length];
254:
255: for (int i = 0; i < attachments.length; i++) {
256:
257: //
258: // valid attachment?
259: //
260: if ((attachments[i] == null)
261: || !attachments[i].exists()
262: || !attachments[i].isFile())
263:
264: throw new EmailException("Attachment \""
265: + attachments[i]
266: + "\" does not exist or is not a file.");
267:
268: emailAttachments[i] = new EmailAttachment();
269: emailAttachments[i].setPath(attachments[i]
270: .getAbsolutePath());
271: }
272:
273: for (int i = 0; i < to.length; i++) {
274:
275: if (isValidAddress(to[i])) {
276:
277: if (logger_.isDebugEnabled()) {
278: logger_.debug("Sending to " + to[i]);
279: }
280:
281: HtmlEmail email = newHtmlEmail();
282: email.addTo(to[i]);
283: email.setFrom(from);
284: email.setSubject(subject);
285:
286: if (text != null)
287: email.setTextMsg(text);
288:
289: if (html != null)
290: email.setHtmlMsg(html);
291:
292: //
293: // add attachments
294: //
295: for (int j = 0; j < emailAttachments.length; j++)
296: email.attach(emailAttachments[j]);
297:
298: email.send();
299: } else {
300: if (logger_.isDebugEnabled()) {
301: logger_.debug("Skipping invalid email address "
302: + to[i]);
303: }
304: }
305: }
306: } catch (EmailException e) {
307: String msg = "Sending html email from " + from + " to "
308: + to + " with subject \"" + subject + "\", text \""
309: + text + "\", html \"" + html
310: + "\", and attachments " + attachments + "\n"
311: + ExceptionUtils.getStackTrace(e);
312: logger_.error(msg);
313: throw new MhfException(msg);
314: }
315: }
316:
317: // properties ///////////////////////////////////////////////////////////////
318:
319: // attributes ///////////////////////////////////////////////////////////////
320:
321: protected static Properties mailProperties_ = new Properties();
322:
323: private static Logger logger_ = Logger.getLogger(Mail.class);
324: }
|