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.FileNotFoundException;
028: import java.io.FileOutputStream;
029: import java.io.IOException;
030: import java.io.InputStream;
031: import java.io.InputStreamReader;
032: import java.io.PrintStream;
033: import java.net.URL;
034: import java.net.URLClassLoader;
035: import java.util.ArrayList;
036: import java.util.Date;
037: import java.util.Iterator;
038: import java.util.List;
039: import java.util.Properties;
040:
041: import javax.mail.Flags;
042: import javax.mail.Folder;
043: import javax.mail.Message;
044: import javax.mail.MessagingException;
045: import javax.mail.Multipart;
046: import javax.mail.NoSuchProviderException;
047: import javax.mail.Part;
048: import javax.mail.Session;
049: import javax.mail.Store;
050: import javax.mail.internet.ContentType;
051: import javax.mail.internet.MimeBodyPart;
052: import javax.mail.internet.MimeUtility;
053: import javax.mail.internet.ParseException;
054: import javax.mail.internet.MimeMessage.RecipientType;
055:
056: import org.apache.commons.logging.Log;
057:
058: import com.bostechcorp.cbesb.common.runtime.CbesbException;
059: import com.bostechcorp.cbesb.common.util.ErrorUtil;
060:
061: /**
062: * @author LPS
063: */
064: public class IMAPService implements IReceiveMailService {
065: private MailPasswordAuthenticator authenticator = null;
066:
067: private Log logger = null;
068:
069: private String url;
070:
071: private String port;
072:
073: private String charset;
074:
075: private Session session;
076:
077: private Store store;
078:
079: private String folder = "INBOX";
080:
081: private String attachDirectory;
082:
083: private boolean textIsHtml = false; // optional variable for the get text
084:
085: // function
086:
087: private String encoding = "";
088:
089: private String body = "";
090:
091: private int level = 0; // aux variable for getText - recursion depth
092:
093: public IMAPService(String URL, String Port, String User,
094: String Password, String charset, boolean useSSL,
095: Properties otherProperties, String attachDirectory)
096: throws MailException {
097:
098: /*
099: *DEFAULT_SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory";
100: *
101: * System.setProperty("mail." + getProtocol() + ".ssl", "true");
102: System.setProperty("mail." + getProtocol() + ".socketFactory.class", getSocketFactory());
103: System.setProperty("mail." + getProtocol() + ".socketFactory.fallback", getSocketFactoryFallback());
104:
105: if (getTrustStore() != null)
106: {
107: System.setProperty("javax.net.ssl.trustStore", getTrustStore());
108: if (getTrustStorePassword() != null)
109: {
110: System.setProperty("javax.net.ssl.trustStorePassword", getTrustStorePassword());
111: }
112: }
113: *
114: */
115:
116: this .url = URL;
117: this .port = Port;
118: this .attachDirectory = attachDirectory;
119: this .charset = charset;
120: // charset check
121: if (this .charset == null || this .charset.trim().length() == 0) {
122: this .charset = (new InputStreamReader(
123: new ByteArrayInputStream(new byte[0])))
124: .getEncoding();
125: }
126: otherProperties.put("mail.mime.charset", this .charset);
127: //otherProperties.put("mail.pop3.disabletop", "false");
128: //otherProperties.put("mail.pop3.forgettopheaders", "false");
129:
130: //
131: authenticator = new MailPasswordAuthenticator(User, Password);
132:
133: otherProperties.put("mail.store.protocol", useSSL ? "imaps"
134: : "imap");
135: //otherProperties.put("mail.host", url);
136: //otherProperties.put("mail.user", authenticator.getPasswordAuthentication().getUserName());
137:
138: otherProperties.put("mail." + (useSSL ? "imaps" : "imap")
139: + ".host", url);
140: otherProperties.put("mail." + (useSSL ? "imaps" : "imap")
141: + ".port", port);
142: otherProperties.put("mail." + (useSSL ? "imaps" : "imap")
143: + ".user", authenticator.getPasswordAuthentication()
144: .getUserName());
145:
146: // creating the session
147: session = Session.getInstance(otherProperties, authenticator);
148: session.setDebugOut(System.out);
149: session.setDebug(false);
150: // creating store
151: try {
152: store = session.getStore(useSSL ? "imaps" : "imap");
153: } catch (NoSuchProviderException e) {
154: throw new MailException(
155: "Failed to get IMAP protocol object - "
156: + e.getMessage(), e);
157: }
158: }
159:
160: /**
161: *
162: * @param debug - tell JavaMail to display or not the debug information
163: * @param Exceptionlog - service logger, if none the System.out will be
164: * used to display the debug information
165: * @param sessionPStream - tell JavaMail where to send the debug information
166: */
167: public void setDebug(boolean debug, Log Exceptionlog,
168: PrintStream sessionPStream) {
169: this .logger = Exceptionlog;
170: session.setDebug(debug);
171: if (sessionPStream != null) {
172: session.setDebugOut(sessionPStream);
173: } else {
174: session.setDebugOut(System.out);
175: }
176: }
177:
178: private void dumpPart(Part p, List<String> attachementsList)
179: throws MessagingException, CbesbException
180:
181: {
182: String ctString = p.getContentType();
183: ContentType ct = null;
184: try {
185: ct = new ContentType(ctString);
186: } catch (ParseException e) {
187: throw new MailException("Invalid content type '" + ctString
188: + "' - ", e.getMessage(), e);
189: }
190:
191: try {
192: // look for text of any kind
193: if (p.isMimeType("text/*")) {
194: //it is possible to be either attachement either body part
195: //so in order to find out just check if disposition is present
196: String disp = p.getDisposition();
197: // many mailers don't include a Content-Disposition, in this case
198: //the part will be treated as body content
199: if (disp == null) {
200: body += (String) p.getContent();//
201: // logger.debug("body in Pop3Service: =============================" + body);
202: //System.out.println("body in Pop3Service: =============================" + body);
203: //System.out.println("Part instance: =============================" + p.getClass().toString());
204: textIsHtml = p.isMimeType("text/html");
205: if (ct != null) {
206: encoding = MimeUtility.javaCharset(ct
207: .getParameter("charset"));
208: } else {
209: encoding = "Unknown";
210: }
211: }
212: //otherwise part is text attachement so we'll
213: //save it in the end of the method
214: } else if (p.isMimeType("multipart/*")) {
215: Multipart mp = (Multipart) p.getContent();
216: level++;
217: int count = mp.getCount();
218: for (int i = 0; i < count; i++)
219: dumpPart(mp.getBodyPart(i), attachementsList);
220: level--;
221: } else if (p.isMimeType("message/rfc822")) {
222:
223: level++;
224: dumpPart((Part) p.getContent(), attachementsList);
225: level--;
226: } else //if content type is image/* ;audio/*; application/*
227: {
228: /*
229: * If we actually want to save the data,
230: * and it's not a MIME type we
231: * know, fetch it and check its Java type.
232: */
233:
234: Object o = p.getContent();
235: long attnum = System.currentTimeMillis();
236: String filename = p.getFileName();
237: if (filename == null) {
238: filename = "Attachment_" + attnum;
239: }
240: //String filename = "Attachment_" + attnum;
241: if (o instanceof String) {
242: createPathToFile(filename);
243: if (saveFile(filename, (String) o))
244: attachementsList.add(getAttachDirectory()
245: + filename);
246: return;
247: } else if (o instanceof InputStream) {
248: createPathToFile(filename);
249: if (saveFile(filename, (InputStream) o))
250: attachementsList.add(getAttachDirectory()
251: + filename);
252: return;
253: } else {
254: createPathToFile(filename);
255: if (saveFile(filename, o.toString()))
256: attachementsList.add(getAttachDirectory()
257: + filename);
258: return;
259: }
260: }
261: } catch (IOException e) {
262: throw new MailException(
263: "Failed to get content for the Mail Part - "
264: + e.getMessage(), e);
265: }
266:
267: /*
268: * If we're saving attachments, write out anything that looks like an
269: * attachment into an appropriately named file. Don't overwrite existing
270: * files to prevent mistakes.
271: */
272: String filename = p.getFileName();
273: long attnum = System.currentTimeMillis();
274: if (level != 0 && !p.isMimeType("multipart/*")
275: && !p.isMimeType("message/*")) {
276: String disp = p.getDisposition();
277: // many mailers don't include a Content-Disposition
278: if (disp != null) {
279: if (filename == null) {
280: filename = "Attachment_" + attnum;
281: }
282: try {
283: // checking if attachement directory exist and
284: // if needed creating the path
285: // if (!exist(getAttachDirectory()))
286: //
287: File f = new File(getAttachDirectory()
288: + getFileName(filename));
289: createPathToFile(getAttachDirectory()
290: + getFileName(filename));
291: if (f.exists()) {
292: // XXXX - could try a series of names, but it is
293: // owerwritting for the moment
294: // filename += "" + attnum;
295: // throw new IOException("file exists");
296: }
297: ((MimeBodyPart) p).saveFile(f);
298: attachementsList.add(getAttachDirectory()
299: + filename);
300: } catch (IOException e) {
301: throw new MailException(
302: "Exception writing attachment to file: '"
303: + filename + "' - "
304: + e.getMessage(), e);
305: }
306: }
307: }
308: }
309:
310: public List<EmailBean> fetchEmails() throws CbesbException {
311: Folder folder;
312: List<EmailBean> emailList = new ArrayList<EmailBean>();
313: try {
314: // connectiong to the Store
315: store.connect(url, authenticator
316: .getPasswordAuthentication().getUserName(),
317: authenticator.getPasswordAuthentication()
318: .getPassword());
319: // getting the folder
320: folder = store.getDefaultFolder();
321: if (folder == null)
322: throw new MailException("No default folder available!");
323: // -- ...and its INBOX --
324: folder = folder.getFolder(getFolder());
325: if (folder == null)
326: throw new MailException(
327: "No IMAP INBOX folder available!");
328: // -- Open the folder for read & delete --
329: folder.open(Folder.READ_WRITE);
330: // -- Get the message wrappers and process them --
331: Message[] msgs = folder.getMessages();
332: for (int i = 0; i < msgs.length; i++) {
333: EmailBean mailBean = new EmailBean();
334: // message envelope section//
335: mailBean.setFrom(msgs[i].getFrom());
336: mailBean.setTo(msgs[i].getRecipients(RecipientType.TO));
337: mailBean.setCc(msgs[i].getRecipients(RecipientType.CC));
338: mailBean.setBcc(msgs[i]
339: .getRecipients(RecipientType.BCC));
340: mailBean.setSubject(msgs[i].getSubject());
341: mailBean.setReplyTo(msgs[i].getReplyTo());
342: mailBean.setReceived(msgs[i].getReceivedDate());
343: mailBean.setSent(msgs[i].getSentDate());
344: mailBean.setReceived(new Date());
345:
346: // Debug section
347: /*
348: System.out.println("-------------->" +msgs[i].getClass().toString());
349: POP3Message popMessage =(POP3Message) msgs[i];
350: System.out.println("popMessage-------------->" +popMessage.getContentType());
351: System.out.println("msgs[i]-------------->" +msgs[i].getContentType());
352: System.out.println("popMessage-------------->" +popMessage.getDisposition());
353: System.out.println("popMessage content instance -------------->" +popMessage.getContent().getClass().toString());
354: System.out.println("msgs[i] content instance -------------->" +msgs[i].getContent().getClass().toString());
355: System.out.println("popMessage filename-------------->" +popMessage.getFileName());
356: System.out.println("popMessage Headers-------------->" +popMessage.getAllHeaders());
357: */
358: //System.out.println("EndHEaders-------------->");
359: // System.out.println("-------------->"+ popMessage.get());
360: //
361: // getting each message
362: List<String> attachementsList = new ArrayList<String>();
363: level = 0;
364: body = "";
365: if (msgs[i].getContentType() != null)
366: //if we are having a good header
367: //of the message then parse it
368: {
369: dumpPart(msgs[i], attachementsList);
370: }
371:
372: mailBean.setBodyContent(body, this .textIsHtml,
373: this .encoding);
374: mailBean.setBodyAttachements(attachementsList);
375:
376: // if (msgs[i].isMimeType("text/*"))
377: // {
378: // mailBean.setBodyContent((String) msgs[i].getContent(),
379: // msgs[i].isMimeType("text/html"), charset);
380: // }
381: // else if (msgs[i].isMimeType("multipart/*"))
382: // {
383: // Multipart multipart = (Multipart) msgs[i].getContent();
384: //
385: // for (int j = 0, n = multipart.getCount(); j < n; j++)
386: // {
387: // Part part = multipart.getBodyPart(j);
388: // String disposition = part.getDisposition();
389: //
390: // if (disposition != null)
391: // {
392: // if (disposition.equals(Part.ATTACHMENT))
393: // {
394: //
395: // // save as attachement
396: // saveFile(getAttachDirectory()
397: // + part.getFileName(), part
398: // .getInputStream());
399: // mailBean
400: // .addBodyAttachements(getAttachDirectory()
401: // + part.getFileName());
402: // } else if ((disposition.equals(Part.INLINE)))
403: // {
404: // MimeBodyPart bodyPart = (MimeBodyPart) part;
405: // if (bodyPart.isMimeType("text/html")
406: // || bodyPart.isMimeType("text/plain"))
407: // {
408: // Boolean isHtml = bodyPart
409: // .isMimeType("text/html");
410: // String enchoding = bodyPart.getEncoding();
411: // String body = (String) bodyPart
412: // .getContent();
413: // // set as body
414: // mailBean.setBodyContent(body, isHtml,
415: // enchoding);
416: // } else
417: // {
418: // // save as attachement
419: // saveFile(getAttachDirectory()
420: // + part.getFileName(), part
421: // .getInputStream());
422: // mailBean
423: // .addBodyAttachements(getAttachDirectory()
424: // + part.getFileName());
425: //
426: // }
427: // }
428: // }/*
429: // * else // we have Unknown Disposition { // save as
430: // * attachement saveFile(getAttachDirectory() +
431: // * part.getFileName(), part.getInputStream());
432: // * mailBean.addBodyAttachements(getAttachDirectory() +
433: // * part.getFileName()); }
434: // */
435: // }
436: // }
437: emailList.add(mailBean);
438: // marking to be deleted
439: msgs[i].setFlag(Flags.Flag.DELETED, true);
440: }
441: // closing the folder and deleting all(marked) the messages from
442: // inside
443: folder.close(true);
444:
445: } catch (MessagingException e) {
446: throw new MailException(
447: "Exception trying to retreive email - "
448: + e.getMessage(), e);
449: }
450: return emailList;
451: }
452:
453: private boolean saveFile(String fileName, InputStream inputStream) {
454: if (inputStream == null)
455: return false;
456: File file = new File(getAttachDirectory() + fileName);
457: FileOutputStream fostream = null;
458: PrintStream pstream = null;
459: //
460: if (!exist(getAttachDirectory()))
461: createPathToFile(getAttachDirectory());
462:
463: // opening output file
464: try {
465: fostream = new FileOutputStream(file);
466: } catch (FileNotFoundException e) {
467: ErrorUtil.printWarn("Exception trying to open file '"
468: + fileName
469: + "' to write attachment. The file is not saved - "
470: + e.getMessage(), e);
471: return false;
472: }
473:
474: if (fostream != null)
475: pstream = new PrintStream(fostream);
476: if (pstream != null)
477: try {
478: int c;
479: while ((c = inputStream.read()) != -1) {
480: pstream.write(c);
481: }
482: } catch (IOException e) {
483: ErrorUtil.printWarn(
484: "Exception writing attachment file '"
485: + fileName
486: + "'. The file is not saved - "
487: + e.getMessage(), e);
488: return false;
489: }
490: return true;
491: }
492:
493: private boolean saveFile(String fileName, String string) {
494: if (string == null)
495: return false;
496: File file = new File(getAttachDirectory() + fileName);
497: FileOutputStream fostream = null;
498: PrintStream pstream = null;
499: //
500: if (!exist(getAttachDirectory()))
501: createPathToFile(getAttachDirectory());
502:
503: // opening output file
504: try {
505: fostream = new FileOutputStream(file);
506: } catch (FileNotFoundException e) {
507: ErrorUtil.printWarn("Exception trying to open file '"
508: + fileName
509: + "' to write attachment. The file is not saved - "
510: + e.getMessage(), e);
511: return false;
512: }
513:
514: if (fostream != null)
515: pstream = new PrintStream(fostream);
516: if (pstream != null)
517: try {
518: byte[] readBuffer = string.getBytes();
519: pstream.write(readBuffer);
520: } catch (IOException e) {
521: ErrorUtil.printWarn(
522: "Exception writing attachment file '"
523: + fileName
524: + "'. The file is not saved - "
525: + e.getMessage(), e);
526: return false;
527: }
528: return true;
529: }
530:
531: /**
532: * @return the attachDirectory
533: */
534: public String getAttachDirectory() {
535: if (attachDirectory.endsWith("/")) {
536: return attachDirectory;
537: }
538: {
539: return attachDirectory + "/";
540: }
541:
542: }
543:
544: protected boolean exist(String fileName) {
545: return (new File(fileName)).exists();
546: }
547:
548: protected boolean createPathToFile(String fileName) {
549: // java.lang.SecurityManager.checkRead(java.lang.String)
550: // java.lang.SecurityManager.checkWrite(java.lang.String)
551: boolean result = false;
552: String onlyPath = fileName;
553: try {
554: if (fileName.endsWith(File.separator)) {
555: onlyPath = onlyPath.substring(0, onlyPath.length() - 1);
556: }
557: onlyPath = onlyPath.substring(0, onlyPath.length()
558: - getFileName(onlyPath).length());
559: result = (new File(onlyPath)).mkdirs();
560: } catch (SecurityException e) {
561: ErrorUtil.printWarn("Failed to create the directory '"
562: + onlyPath + "'. Check R/W permissions - "
563: + e.getMessage(), e);
564: }
565: return result;
566: }
567:
568: protected String getFileName(String fileName) {
569: return (new File(fileName)).getName();
570: }
571:
572: public static void main(String[] args) throws Exception {
573: IMAPService pop3 = new IMAPService("localhost", "143",
574: "mail@lps.lps", "ok", "ASCII", false, System
575: .getProperties(), "C:/Temp/temp/temp");
576: List mails = pop3.fetchEmails();
577: if (mails.size() > 0) {
578: System.out.println("You've got mail: " + mails.size());
579: for (Iterator iter = mails.iterator(); iter.hasNext();) {
580: EmailBean element = (EmailBean) iter.next();
581: System.out
582: .println("Begin----------------------------------------");
583: System.out.println(element.getDataEnvelope());
584: System.out
585: .println("End------------------------------------------");
586: }
587: } else {
588: System.out.println("No mail.");
589: }
590: }
591:
592: public String getFolder() {
593: return this .folder;
594: }
595:
596: public void setFolder(String folder) {
597: this.folder = folder;
598: }
599:
600: }
|