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