001: /*
002: * This file is part of PFIXCORE.
003: *
004: * PFIXCORE is free software; you can redistribute it and/or modify
005: * it under the terms of the GNU Lesser General Public License as published by
006: * the Free Software Foundation; either version 2 of the License, or
007: * (at your option) any later version.
008: *
009: * PFIXCORE is distributed in the hope that it will be useful,
010: * but WITHOUT ANY WARRANTY; without even the implied warranty of
011: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
012: * GNU Lesser General Public License for more details.
013: *
014: * You should have received a copy of the GNU Lesser General Public License
015: * along with PFIXCORE; if not, write to the Free Software
016: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
017: *
018: */
019:
020: package de.schlund.pfixcore.util.email;
021:
022: import java.util.Date;
023: import java.util.Iterator;
024: import java.util.Map;
025: import java.util.Properties;
026: import java.util.Set;
027:
028: import javax.mail.Address;
029: import javax.mail.Message;
030: import javax.mail.MessagingException;
031: import javax.mail.NoSuchProviderException;
032: import javax.mail.SendFailedException;
033: import javax.mail.Session;
034: import javax.mail.Transport;
035: import javax.mail.internet.AddressException;
036: import javax.mail.internet.InternetAddress;
037: import javax.mail.internet.MimeMessage;
038:
039: import org.apache.oro.text.perl.MalformedPerl5PatternException;
040: import org.apache.oro.text.perl.Perl5Util;
041:
042: /**
043: * Utility class for sending mails via java mail-api.
044: *
045: * @author <a href="mailto: haecker@schlund.de">Joerg Haecker</a>
046: */
047:
048: public class EmailSender {
049:
050: // private static Logger LOG = Logger.getLogger(EmailSender.class);
051: private static final String CHARSET = "ISO-8859-15";
052:
053: /**
054: * Send an email (without headers).
055: *
056: * @param subject A String specifying the mail subject. Not null.
057: * @param text The text the mail should contain. Not null.
058: * @param to A String arry specifying the recipients. Not null.
059: * @param from A String specifying the from address. Not null.
060: * @param smtphost A String specifying the smtp-server to use. Not null.
061: * @throws EmailSenderException on errors when trying to send the mail.
062: * @throws IllegalArgumentExceptionwhen trying to pass NPs as paramters.
063: */
064: public static void sendMail(String subject, String text,
065: String[] to, String from, String smtphost)
066: throws EmailSenderException {
067: sendMail(subject, text, null, to, from, smtphost, null, null,
068: false);
069: }
070:
071: /**
072: * Send an email (without headers).
073: *
074: * @param subject A String specifying the mail subject. Not null.
075: * @param text The text the mail should contain. Not null.
076: * @param to A String arry specifying the recipients. Not null.
077: * @param from A String specifying the from address. Not null.
078: * @param smtphost A String specifying the smtp-server to use. Not null.
079: * @param authuser username to use for authentication against the mail server.
080: * If set to <code>null</code>, no authentication will be used.
081: * @param authpassword password to use for authentication against the mail server.
082: * If set to <code>null</code>, no authentication will be used.
083: * @throws EmailSenderException on errors when trying to send the mail.
084: * @throws IllegalArgumentExceptionwhen trying to pass NPs as paramters.
085: */
086: public static void sendMail(String subject, String text,
087: String[] to, String from, String smtphost, String authuser,
088: String authpassword) throws EmailSenderException {
089: sendMail(subject, text, null, to, from, smtphost, authuser,
090: authpassword, false);
091: }
092:
093: /**
094: * Send an email.
095: *
096: * @param subject A String specifying the mail subject. Not null.
097: * @param text The text the mail should contain. Not null.
098: * @param headers A Map contain strings as key and values, these headers will be
099: * appended to the headers of the email. Maybe null.
100: * @param to A String arry specifying the recipients. Not null.
101: * @param from A String specifying the from address. Not null.
102: * @param smtphost A String specifying the smtp-server to use. Not null.
103: * @throws EmailSenderException on errors when trying to send the mail.
104: * @throws IllegalArgumentExceptionwhen trying to pass NPs as paramters.
105: */
106: public static void sendMail(String subject, String text,
107: Map<String, String> headers, String[] to, String from,
108: String smtphost) throws EmailSenderException {
109: sendMail(subject, text, headers, to, from, smtphost, null,
110: null, false);
111: }
112:
113: /**
114: * Send an email.
115: *
116: * @param subject A String specifying the mail subject. Not null.
117: * @param text The text the mail should contain. Not null.
118: * @param headers A Map contain strings as key and values, these headers will be
119: * appended to the headers of the email. Maybe null.
120: * @param to A String arry specifying the recipients. Not null.
121: * @param from A String specifying the from address. Not null.
122: * @param smtphost A String specifying the smtp-server to use. Not null.
123: * @param authuser username to use for authentication against the mail server.
124: * If set to <code>null</code>, no authentication will be used.
125: * @param authpassword password to use for authentication against the mail server.
126: * If set to <code>null</code>, no authentication will be used.
127: * @param secure flag indicating whether to use the STARTTLS command if the server
128: * supports it.
129: * @throws EmailSenderException on errors when trying to send the mail.
130: * @throws IllegalArgumentExceptionwhen trying to pass NPs as paramters.
131: */
132: public static void sendMail(String subject, String text,
133: Map<String, String> headers, String[] to, String from,
134: String smtphost, String authuser, String authpassword,
135: boolean secure) throws EmailSenderException {
136:
137: if (subject == null)
138: throw new IllegalArgumentException(
139: "EmailSender: A NP as subject is not allowed!");
140:
141: if (text == null)
142: throw new IllegalArgumentException(
143: "EmailSender: A NP as text is not allowed!");
144:
145: if (to == null)
146: throw new IllegalArgumentException(
147: "EmailSender: A NP as recipient-list is not allowed!");
148:
149: for (int i = 0; i < to.length; i++) {
150: if (to[i] == null || to[i].equals("")) {
151: throw new IllegalArgumentException(
152: "EmailSender: To address[" + i
153: + "] not valid: '" + to[i] + "'");
154: }
155: }
156:
157: if (from == null)
158: throw new IllegalArgumentException(
159: "EmailSender: A NP as from address is not allowed!");
160:
161: if (smtphost == null)
162: throw new IllegalArgumentException(
163: "EmailSender: A NP as SMTP host is not allowed!");
164:
165: Properties properties = new Properties();
166: properties.put("mail.smtp.host", smtphost);
167: if (secure) {
168: properties.setProperty("mail.smtp.starttls.enable", "true");
169: }
170: if (authuser != null && authpassword != null) {
171: properties.setProperty("mail.smtp.auth", "true");
172: }
173: Session session = Session.getInstance(properties);
174: MimeMessage msg = new MimeMessage(session);
175:
176: StringBuffer strError = new StringBuffer();
177:
178: //remove all new lines from subject
179: Perl5Util perl = new Perl5Util();
180: try {
181: String newsubject = perl.substitute("s#\n##", subject);
182: subject = newsubject;
183: } catch (MalformedPerl5PatternException e) {
184: strError.append("Caught " + e.getClass().getName() + "\n");
185: strError.append("Message: " + e.getMessage() + "\n");
186: throw new EmailSenderException(strError.toString());
187: }
188:
189: // handle to addresses
190: InternetAddress[] toaddresses = new InternetAddress[to.length];
191: for (int i = 0; i < to.length; i++) {
192: try {
193: toaddresses[i] = new InternetAddress(to[i]);
194: } catch (AddressException e) {
195: strError.append("Caught " + e.getClass().getName()
196: + "\n");
197: strError.append("Text: " + to[i]
198: + " is not a valid address!" + "\n");
199: strError.append("Message: " + e.getMessage() + "\n");
200: throw new EmailSenderException(strError.toString());
201: }
202: }
203:
204: // handle from address
205: InternetAddress fromaddress = null;
206: try {
207: fromaddress = new InternetAddress(from);
208: } catch (AddressException e) {
209: strError.append("Caught " + e.getClass().getName() + "\n");
210: strError.append("Text: " + from
211: + " is not a valid address!" + "\n");
212: strError.append("Message: " + e.getMessage() + "\n");
213: throw new EmailSenderException(strError.toString());
214: }
215:
216: // got everything, now send mail
217: try {
218: msg.setText(text, CHARSET);
219: msg.setHeader("Content-Type", "text/plain; charset="
220: + CHARSET);
221: msg.setHeader("Content-Transfer-Encoding", "8bit");
222:
223: if (headers != null) {
224: Set<String> keys = headers.keySet();
225:
226: for (Iterator<String> iter = keys.iterator(); iter
227: .hasNext();) {
228: String key = iter.next();
229: String value = headers.get(key);
230: msg.setHeader(key, value);
231: }
232:
233: }
234:
235: msg.setRecipients(Message.RecipientType.TO, toaddresses);
236: msg.setSubject(subject, CHARSET);
237: msg.setFrom(fromaddress);
238: msg.setSentDate(new Date());
239:
240: Transport transport;
241: try {
242: transport = session.getTransport("smtp");
243: } catch (NoSuchProviderException e) {
244: throw new EmailSenderException(
245: "Could not get a transport for smtp protocol",
246: e);
247: }
248:
249: if (authuser != null && authpassword != null) {
250: transport.connect(smtphost, authuser, authpassword);
251: } else {
252: transport.connect(smtphost, null, null);
253: }
254:
255: transport.sendMessage(msg, msg.getAllRecipients());
256: } catch (MessagingException mex) {
257: Exception ex = mex;
258: strError
259: .append("Caught " + mex.getClass().getName() + "\n");
260: strError.append("Message: " + mex.getMessage() + "\n\n");
261: do {
262: if (ex instanceof SendFailedException) {
263: SendFailedException sfex = (SendFailedException) ex;
264: Address[] invalid = sfex.getInvalidAddresses();
265: if (invalid != null) {
266: strError.append("** Invalid Addresses\n");
267: if (invalid != null) {
268: for (int i = 0; i < invalid.length; i++)
269: strError
270: .append(" " + invalid[i] + "\n");
271: }
272: }
273: Address[] validUnsent = sfex
274: .getValidUnsentAddresses();
275: if (validUnsent != null) {
276: strError
277: .append(" ** ValidUnsent Addresses\n");
278: if (validUnsent != null) {
279: for (int i = 0; i < validUnsent.length; i++)
280: strError.append(" " + validUnsent[i]
281: + "\n");
282: }
283: }
284: Address[] validSent = sfex.getValidSentAddresses();
285: if (validSent != null) {
286: strError.append(" ** ValidSent Addresses\n");
287: if (validSent != null) {
288: for (int i = 0; i < validSent.length; i++)
289: strError.append(" " + validSent[i]
290: + "\n");
291: }
292: }
293: }
294: strError.append("\n");
295: if (ex instanceof MessagingException)
296: ex = ((MessagingException) ex).getNextException();
297: else
298: ex = null;
299: } while (ex != null);
300: throw new EmailSenderException(strError.toString());
301: }
302: }
303:
304: }
|