001: /**
002: * ChainBuilder ESB
003: * Visual Enterprise Integration
004: *
005: * Copyright (C) 2006 Bostech Corporation
006: *
007: * This program is free software; you can redistribute it and/or modify it
008: * under the terms of the GNU General Public License as published by the
009: * Free Software Foundation; either version 2 of the License, or (at your option)
010: * any later version.
011: *
012: * This program is distributed in the hope that it will be useful,
013: * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
014: * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
015: * for more details.
016: *
017: * You should have received a copy of the GNU General Public License along with
018: * this program; if not, write to the Free Software Foundation, Inc.,
019: * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020: *
021: *
022: * $Id$
023: */package com.bostechcorp.cbesb.runtime.email;
024:
025: import java.io.ByteArrayInputStream;
026: import java.io.File;
027: import java.io.InputStreamReader;
028: import java.io.PrintStream;
029: import java.util.ArrayList;
030: import java.util.Date;
031: import java.util.List;
032: import java.util.Properties;
033:
034: import javax.activation.DataHandler;
035: import javax.activation.FileDataSource;
036: import javax.mail.MessagingException;
037: import javax.mail.Multipart;
038: import javax.mail.NoSuchProviderException;
039: import javax.mail.Part;
040: import javax.mail.Session;
041: import javax.mail.internet.InternetAddress;
042: import javax.mail.internet.MimeBodyPart;
043: import javax.mail.internet.MimeMessage;
044: import javax.mail.internet.MimeMultipart;
045: import javax.mail.internet.MimeUtility;
046:
047: import org.apache.commons.logging.Log;
048:
049: import com.bostechcorp.cbesb.common.runtime.CbesbException;
050: import com.bostechcorp.cbesb.common.runtime.ConfigurationException;
051: import com.bostechcorp.cbesb.common.runtime.DataContentException;
052: import com.sun.mail.smtp.SMTPTransport;
053:
054: /**
055: * @author LPS
056: */
057: public class SMTPService {
058:
059: private String url = "";
060:
061: private String port = "";
062:
063: private String charset = "";
064:
065: private Session session = null;
066:
067: private SMTPTransport transport = null;
068:
069: private MimeMessage mimeMessage = null;
070:
071: private MimeBodyPart bodyPart = null;
072:
073: private List<MimeBodyPart> attachList = null;
074:
075: private MailPasswordAuthenticator authenticator = null;
076:
077: private Log logger = null;
078:
079: private boolean useAuthentification;
080:
081: /**
082: * @param URL
083: * @param Port
084: * @param User
085: * @param Password
086: * @param otherProperties -
087: * System.getProperties()
088: */
089: public SMTPService(String URL, String Port, String User,
090: String Password, String charset, boolean useSSL,
091: boolean useAuthentication, Properties otherProperties)
092: throws CbesbException {
093:
094: this .url = URL;
095: this .port = Port;
096: this .charset = charset;
097: // charset check
098: if (this .charset == null || this .charset.trim().length() == 0) {
099: this .charset = (new InputStreamReader(
100: new ByteArrayInputStream(new byte[0])))
101: .getEncoding();
102: }
103: this .charset = MimeUtility.mimeCharset(this .charset);
104: otherProperties.put("mail.mime.charset", this .charset);
105: //
106: this .useAuthentification = useAuthentication;
107: authenticator = new MailPasswordAuthenticator(User, Password);
108: if (useSSL) {
109: otherProperties.put("mail.transport.protocol", "smtps");
110: otherProperties.put("mail.smtps.host", url);
111: otherProperties.put("mail.smtps.port", port);
112:
113: if (useAuthentication) {
114: otherProperties.put("mail.smtps.auth", "true");
115: otherProperties.put("mail.submitter", authenticator
116: .getPasswordAuthentication().getUserName());
117: } else {
118: otherProperties.put("mail.smtps.auth", "false");
119: }
120:
121: } else {
122: otherProperties.put("mail.transport.protocol", "smtp");
123: otherProperties.put("mail.smtp.host", url);
124: otherProperties.put("mail.smtp.port", port);
125:
126: if (useAuthentication) {
127: otherProperties.put("mail.smtp.auth", "true");
128: otherProperties.put("mail.submitter", authenticator
129: .getPasswordAuthentication().getUserName());
130: } else {
131: otherProperties.put("mail.smtp.auth", "false");
132: }
133: }
134: // creating the session
135: session = Session.getInstance(otherProperties, authenticator);
136:
137: session.setDebugOut(System.out);
138: session.setDebug(false);
139: // creating the message
140: mimeMessage = new MimeMessage(session);
141: // setting the transport
142: try {
143: transport = (SMTPTransport) session
144: .getTransport(useSSL ? "smtps" : "smtp");
145: // transport = session.getTransport();
146: } catch (NoSuchProviderException e) {
147: MailException me = new MailException(
148: "Failed to get SMTP protocol object. - "
149: + e.getMessage(), e);
150: me
151: .setRemedy("Check that the configuration is using a valid protocol.");
152: throw me;
153: // if (logger != null) {
154: // logger.error("SmtpService caught exception: ", e);
155: // } else
156: // e.printStackTrace();
157: }
158: }
159:
160: /**
161: *
162: * @param debug -
163: * tell JavaMail to display or not the debug information
164: * @param Exceptionlog -
165: * service logger, if none the System.out will be used to display
166: * the debug information
167: * @param sessionPStream -
168: * tell JavaMail where to send the debug information
169: */
170: public void setDebug(boolean debug, Log Exceptionlog,
171: PrintStream sessionPStream) {
172: this .logger = Exceptionlog;
173: session.setDebug(debug);
174: if (sessionPStream != null) {
175: session.setDebugOut(sessionPStream);
176: } else {
177: session.setDebugOut(System.out);
178: }
179: }
180:
181: public void setMessageAttributes(String fromAddress,
182: String toAddress, String ccAddress, String bccAddreses,
183: String subject) throws CbesbException {
184: assert mimeMessage != null;
185: try {
186: // sent date
187: mimeMessage.setSentDate(new Date());
188: // subject
189: mimeMessage.setSubject(subject);
190: // From
191: if (fromAddress == null || fromAddress.length() == 0) {
192: throw new ConfigurationException(
193: "The FROM field is null or an empty string.");
194: } else {
195: mimeMessage.setFrom(new InternetAddress(fromAddress));
196: }
197: // To
198: if ((toAddress != null) && (toAddress.length() > 0)) {
199: // if(toAddress.contains(";"))
200:
201: mimeMessage.addRecipients(MimeMessage.RecipientType.TO,
202: InternetAddress.parse(toAddress.replace(";",
203: ",")));
204: } else {
205: throw new ConfigurationException(
206: "The TO field is null or an empty string.");
207: }
208: // CC
209: if ((ccAddress != null) && (ccAddress.length() > 0)) {
210:
211: mimeMessage.addRecipients(MimeMessage.RecipientType.CC,
212: InternetAddress.parse(ccAddress.replace(";",
213: ",")));
214: }
215: // Bcc
216: if ((bccAddreses != null) && (bccAddreses.length() > 0)) {
217: mimeMessage.addRecipients(
218: MimeMessage.RecipientType.BCC, InternetAddress
219: .parse(bccAddreses.replace(";", ",")));
220: }
221: } catch (MessagingException e) {
222: throw new ConfigurationException(
223: "Exception while setting email attributes - "
224: + e.getMessage(), e);
225: }
226: }
227:
228: public void setMessageBody(String body, boolean isHTML)
229: throws CbesbException {
230: String argument = "";
231: bodyPart = new MimeBodyPart();
232: if (isHTML) {
233: argument += "text/html";
234: } else {
235: argument += "text/plain";
236: }
237:
238: argument += "; charset=" + this .charset;
239:
240: try {
241: bodyPart.setContent(body, argument);
242: } catch (MessagingException e) {
243: throw new ConfigurationException(
244: "Exception while setting the email message body - "
245: + e.getMessage(), e);
246: }
247: }
248:
249: protected String getFileName(String fileName) {
250: return (new File(fileName)).getName();
251: }
252:
253: public void setMessageAttachements(List<String> attachements)
254: throws CbesbException {
255: attachList = new ArrayList<MimeBodyPart>();
256: for (String fileName : attachements) {
257: MimeBodyPart attachFilePart = new MimeBodyPart();
258: FileDataSource fds = new FileDataSource(fileName);
259: try {
260: attachFilePart.setDataHandler(new DataHandler(fds));
261: attachFilePart.setFileName(fds.getName());
262: attachFilePart.setDisposition(Part.ATTACHMENT);
263: attachFilePart.setContentID(fileName);
264: attachFilePart.setDescription("CBESB Mail Service");
265: } catch (MessagingException e) {
266: // if (logger != null) {
267: // logger.error("SmtpService caught exception: ", e);
268: // } else
269: // e.printStackTrace();
270: throw new DataContentException(
271: "Exception while setting email attachment(s) - "
272: + e.getMessage(), e);
273: }
274: attachList.add(attachFilePart);
275: }
276: }
277:
278: public void sendEmailMessage() throws CbesbException {
279: // composing the mail...
280: Multipart multipart = new MimeMultipart();
281: try {
282: // adding the body
283: multipart.addBodyPart(bodyPart);
284: // adding the attachements
285: if (attachList != null && attachList.size() != 0)
286: for (MimeBodyPart attachement : attachList) {
287: multipart.addBodyPart(attachement);
288: }
289: // setting the message Body
290: mimeMessage.setContent(multipart);
291: // executing the mail transport
292: } catch (MessagingException e) {
293: throw new DataContentException(
294: "Exception while creating email message - "
295: + e.getMessage(), e);
296: }
297:
298: try {
299: if (useAuthentification) {
300: transport.connect(this .url, authenticator
301: .getPasswordAuthentication().getUserName(),
302: authenticator.getPasswordAuthentication()
303: .getPassword());
304: } else {
305: transport.connect();
306: }
307: } catch (MessagingException e) {
308: MailConnectionException mce = new MailConnectionException(
309: "Failed to connect to the SMTP Host : '" + this .url
310: + "' - " + e.getMessage(), e);
311: mce
312: .setRemedy("Check that the settings for host and port are correct and verify the server is up.");
313: throw mce;
314: }
315:
316: try {
317: transport.sendMessage(mimeMessage, mimeMessage
318: .getRecipients(MimeMessage.RecipientType.TO));
319: if (mimeMessage.getRecipients(MimeMessage.RecipientType.CC) != null) {
320: transport.sendMessage(mimeMessage, mimeMessage
321: .getRecipients(MimeMessage.RecipientType.CC));
322: }
323: if (mimeMessage
324: .getRecipients(MimeMessage.RecipientType.BCC) != null) {
325: transport.sendMessage(mimeMessage, mimeMessage
326: .getRecipients(MimeMessage.RecipientType.BCC));
327: }
328: transport.close();
329: } catch (MessagingException e) {
330: throw new ConfigurationException(
331: "Exception while sending the email message to SMTP host - "
332: + e.getMessage(), e);
333: }
334: }
335:
336: // public static void main(String[] args) {
337: // try {
338: // SMTPService service = new SMTPService("smtp.263xmail.com", "25",
339: // "cbesb@inprosystem.com", "cbesb", "", false, true, new Properties());
340: // service.setMessageAttributes("cbesb@inprosystem.com", "cbesb@inprosystem.com",
341: // "j.zhang@inprosystem.com", null, "Test - send by java main().");
342: // service.setMessageBody("message Body Content.", true);
343: // List<String> al = new ArrayList<String>();
344: // al.add("c:/Temp/asd.txt");
345: // service.setMessageAttachements(al);
346: // service.sendEmailMessage();
347: // } catch (Exception e) {
348: // e.printStackTrace();
349: // }
350: // }
351: }
|