KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencrx > mail > servlet > MailStore


1 /*
2  * ====================================================================
3  * Project: opencrx, http://www.opencrx.org/
4  * Name: $Id: MailStore.java,v 1.1 2006/03/29 15:43:36 wfro Exp $
5  * Description: openCRX EMailImporter
6  * Revision: $Revision: 1.1 $
7  * Owner: CRIXP AG, Switzerland, http://www.crixp.com
8  * Date: $Date: 2006/03/29 15:43:36 $
9  * ====================================================================
10  *
11  * This software is published under the BSD license
12  * as listed below.
13  *
14  * Copyright (c) 2004-2006, CRIXP Corp., Switzerland
15  * All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  *
21  * * Redistributions of source code must retain the above copyright
22  * notice, this list of conditions and the following disclaimer.
23  *
24  * * Redistributions in binary form must reproduce the above copyright
25  * notice, this list of conditions and the following disclaimer in
26  * the documentation and/or other materials provided with the
27  * distribution.
28  *
29  * * Neither the name of CRIXP Corp. nor the names of the contributors
30  * to openCRX may be used to endorse or promote products derived
31  * from this software without specific prior written permission
32  *
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
35  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
36  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
37  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
39  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
40  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
41  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
43  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
45  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
46  * POSSIBILITY OF SUCH DAMAGE.
47  *
48  * ------------------
49  *
50  * This product includes software developed by the Apache Software
51  * Foundation (http://www.apache.org/).
52  *
53  * This product includes software developed by contributors to
54  * openMDX (http://www.openmdx.org/)
55  */

56 package org.opencrx.mail.servlet;
57
58 import java.util.Properties JavaDoc;
59
60 import javax.mail.Flags JavaDoc;
61 import javax.mail.Folder JavaDoc;
62 import javax.mail.FolderNotFoundException JavaDoc;
63 import javax.mail.Message JavaDoc;
64 import javax.mail.MessagingException JavaDoc;
65 import javax.mail.NoSuchProviderException JavaDoc;
66 import javax.mail.Session JavaDoc;
67 import javax.mail.Store JavaDoc;
68 import javax.mail.URLName JavaDoc;
69 import javax.mail.internet.MimeMessage JavaDoc;
70
71 import org.openmdx.application.log.AppLog;
72 import org.openmdx.base.exception.ServiceException;
73
74 import com.sun.mail.imap.IMAPSSLStore;
75 import com.sun.mail.imap.IMAPStore;
76 import com.sun.mail.pop3.POP3SSLStore;
77 import com.sun.mail.pop3.POP3Store;
78
79 public class MailStore {
80
81   //-------------------------------------------------------------------------
82
public MailStore(
83       MailServerConfig config
84   ) {
85     super();
86     this.config = config;
87   }
88
89   //-------------------------------------------------------------------------
90
/**
91    * Opens the protocol specific store for the configured mail server. Whether
92    * SSL is used depends upon the current server configuration held in this
93    * instance.
94    *
95    */

96   public void openStore (
97   ) throws ServiceException {
98
99     AppLog.info("Fetching emails using the following configuration:");
100     AppLog.info(config.toString());
101
102     // setup mail and mail protocol specific properties with values specified in configuration
103
Properties JavaDoc mailProps = new Properties JavaDoc();
104     mailProps.setProperty("mail.debug", config.debugMode == false ? "false" : "true");
105     mailProps.setProperty("mail.store.protocol", config.mailProtocol);
106     if(config.isSslRequired) {
107         // mailProps.setProperty("mail.SSLSocketFactory.class",
108
// SendMailSSLSocketFactory.class.getName());
109
// mailProps.setProperty("mail." + mailProtocol +
110
// ".SSLSocketFactory.class",
111
// SendMailSSLSocketFactory.class.getName());
112

113         // WARNING: do NOT use mail." + mailProtocol + ".socketFactory.class due a bug in
114
// com.sun.mail.util.SocketFetcher.
115
// SocketFetcher tries to do the initial connect with an SSL socket which
116
// fails. With mail.SSLSocketFactory.class the initial connect is done with a non-SSL
117
// socket and only if the mail server supports STARTTLS does an upgrade to SSL.
118
// DO NOT FORGET to set mail.SSLSocketFactory.class as a system property.
119
// mailProps.setProperty("mail." + serverConfig.mailProtocol + ".socketFactory.class", SendMailSSLSocketFactory.class.getName());
120

121         mailProps.setProperty(
122             "mail." + config.mailProtocol + ".socketFactory.fallback",
123             "false"
124         );
125         mailProps.setProperty(
126             "mail." + config.mailProtocol + ".socketFactory.port",
127             "" + this.config.getMailPort()
128         );
129         // TODO: Check whether it is possible and/or necessary to set starttls option
130
// mailProps.setProperty("mail." + mailProtocol + ".starttls.enable", "true");
131
}
132     if(IMAP_MODE.equals(config.mailProtocol)) {
133         mailProps.setProperty(
134             "mail.imap.port",
135             "" + this.config.getMailPort()
136         );
137     }
138     else {
139         mailProps.setProperty(
140             "mail.pop3.port",
141             "" + this.config.getMailPort()
142         );
143     }
144     Session JavaDoc mailSession = Session.getDefaultInstance(mailProps, null);
145     
146     // if debug mode for email access is configured, enable it
147
if(config.debugMode) {
148         mailSession.setDebug(true);
149         mailSession.setDebugOut(System.err);
150     }
151
152     // construct the URL to connect to the mail server using
153
// the configured protocol, account name, password, server and port
154
URLName JavaDoc url = new URLName JavaDoc(
155         config.mailProtocol +
156         "://" +
157         config.mailAccount +
158         ":" +
159         config.mailPassword +
160         "@" +
161         config.mailServer +
162         ":" +
163         this.config.getMailPort()
164     );
165
166     try {
167         // create a store according to the configured protocol and SSL
168
// settings
169
if(IMAP_MODE.equalsIgnoreCase(config.mailProtocol)) {
170             this.store = this.config.isSslRequired
171                 ? new IMAPSSLStore(mailSession, url)
172                 : new IMAPStore(mailSession, url);
173         }
174         else {
175             this.store = config.isSslRequired
176                 ? new POP3SSLStore(mailSession, url)
177                 : new POP3Store(mailSession, url);
178         }
179
180         // connect the mail store either using the default port or the
181
// configured one
182
if(this.config.getMailPort() == null) {
183             this.store.connect(
184                 this.config.getMailServer(),
185                 this.config.getMailAccount(),
186                 this.config.getMailPassword()
187             );
188         }
189         else {
190             this.store.connect(
191                 this.config.getMailServer(),
192                 this.config.getMailPort().intValue(),
193                 this.config.getMailAccount(),
194                 this.config.getMailPassword()
195             );
196         }
197       }
198       catch (NoSuchProviderException JavaDoc e) {
199           AppLog.error("Could not establish connection to EMail provider");
200           ServiceException e0 = new ServiceException(e);
201           AppLog.error(e0.getMessage(), e0.getCause(), 1);
202           throw e0;
203       }
204       catch (MessagingException JavaDoc e) {
205           AppLog.error("Could not establish connection to EMail provider");
206           ServiceException e0 = new ServiceException(e);
207           AppLog.error(e0.getMessage(), e0.getCause(), 1);
208           throw e0;
209       }
210   }
211
212   //-------------------------------------------------------------------------
213
/**
214    * Reads the recent emails from a configured mail server either using POP3 or
215    * IMAP protocol and returns them.
216    *
217    * @param mailFolderName the name of the folder to be opened and read the messages from
218    */

219   public SimpleMimeMessage[] getMessages(
220   ) throws ServiceException {
221       SimpleMimeMessage readMsgs[] = new SimpleMimeMessage[]{};
222       if(this.folder != null) {
223         try {
224           Message JavaDoc[] messages = folder.getMessages();
225           readMsgs = new SimpleMimeMessage[messages.length];
226           for(int i = 0; i < messages.length; i++) {
227               Message JavaDoc message = messages[i];
228               if(message instanceof MimeMessage JavaDoc) {
229                 MimeMessage JavaDoc mimeMsg = (MimeMessage JavaDoc) message;
230                 readMsgs[i] = new SimpleMimeMessage(mimeMsg, true);
231                 if(AppLog.isTraceOn()) {
232                     AppLog.trace("Read email: " + readMsgs[i].toString());
233                 }
234               }
235           }
236         }
237         catch(NoSuchProviderException JavaDoc e) {
238             AppLog.error("Could not establish connection to EMail provider");
239             ServiceException e0 = new ServiceException(e);
240             AppLog.error(e0.getMessage(), e0.getCause(), 1);
241             throw e0;
242         }
243         catch(MessagingException JavaDoc e) {
244             AppLog.error("Exception while trying to get messages from folder '" + this.folder.getName() + "'");
245             ServiceException e0 = new ServiceException(e);
246             AppLog.error(e0.getMessage(), e0.getCause(), 1);
247             throw e0;
248         }
249      }
250      return readMsgs;
251   }
252
253   //-------------------------------------------------------------------------
254
public void openFolder(
255       String JavaDoc name
256   ) throws ServiceException {
257       try {
258           this.folder = store.getFolder(
259               name == null
260                   ? DEFAULT_FOLDERNAME
261                   : name
262               );
263           this.folder.open(Folder.READ_WRITE);
264       }
265       catch(FolderNotFoundException JavaDoc e) {
266           AppLog.error("Could not open the specified folder '" + name + "'");
267           ServiceException e0 = new ServiceException(e);
268           AppLog.error(e0.getMessage(), e0.getCause(), 1);
269           throw e0;
270       }
271       catch(MessagingException JavaDoc e) {
272           AppLog.error("Exception while opening folder '" + name + "'");
273           ServiceException e0 = new ServiceException(e);
274           AppLog.error(e0.getMessage(), e0.getCause(), 1);
275           throw e0;
276       }
277   }
278
279   //-------------------------------------------------------------------------
280
public void closeFolder(
281   ) {
282       if(this.folder != null) {
283           try {
284               this.folder.close(true);
285           } catch(Exception JavaDoc e) {}
286       }
287   }
288   
289   //-------------------------------------------------------------------------
290
/**
291    * Finally close the store currently in use.
292    *
293    */

294   public void closeStore () {
295     try {
296       store.close();
297     } catch (MessagingException JavaDoc e) {
298       AppLog.warning("Could not clean up resources");
299       System.err.println("Could not clean up after importing");
300     }
301   }
302
303   // -----------------------------------------------------------------------
304
// Members
305
// -----------------------------------------------------------------------
306
public static final String JavaDoc POP3_MODE = "pop3";
307   public static final String JavaDoc IMAP_MODE = "imap";
308   public static final String JavaDoc DEFAULT_FOLDERNAME = "INBOX";
309
310   private Store JavaDoc store = null;
311   private Folder JavaDoc folder = null;
312   private MailServerConfig config = null;
313
314 }
315
316 // --- End of File -----------------------------------------------------------
Popular Tags