KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jetspeed > modules > actions > portlets > email > Email


1 /*
2  * Copyright 2000-2001,2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.jetspeed.modules.actions.portlets.email;
18
19 //JavaMail
20

21 import javax.mail.Session JavaDoc;
22 import javax.mail.Store JavaDoc;
23 import javax.mail.Folder JavaDoc;
24 import javax.mail.AuthenticationFailedException JavaDoc;
25 import javax.mail.NoSuchProviderException JavaDoc;
26 import javax.mail.Message JavaDoc;
27 import javax.mail.Transport JavaDoc;
28 import javax.mail.Address JavaDoc;
29 import javax.mail.Multipart JavaDoc;
30 import javax.mail.Flags JavaDoc;
31 import javax.mail.Part JavaDoc;
32 import javax.mail.Header JavaDoc;
33
34 import javax.mail.internet.MimeMessage JavaDoc;
35 import javax.mail.internet.InternetAddress JavaDoc;
36 import javax.mail.internet.MimeBodyPart JavaDoc;
37 import javax.mail.internet.MimeMultipart JavaDoc;
38
39 import javax.activation.DataSource JavaDoc;
40 import javax.activation.FileDataSource JavaDoc;
41 import javax.activation.DataHandler JavaDoc;
42
43 import com.sun.mail.imap.IMAPFolder;
44
45 import org.apache.turbine.util.upload.FileItem;
46 import org.apache.turbine.services.servlet.TurbineServlet;
47
48 import java.io.File JavaDoc;
49
50 //util
51
import java.util.List JavaDoc;
52 import java.util.Enumeration JavaDoc;
53 import java.util.Properties JavaDoc;
54 import java.util.Vector JavaDoc;
55 import java.util.Hashtable JavaDoc;
56
57 //tdk2.2 version
58
import org.apache.torque.util.Criteria;
59
60 import org.apache.jetspeed.om.apps.email.EmailInboxPeer;
61 import org.apache.jetspeed.om.apps.email.EmailInbox;
62
63 //for logging
64
import org.apache.commons.logging.Log;
65 import org.apache.commons.logging.LogFactory;
66
67 public class Email
68 {
69
70     private static Log log = LogFactory.getLog(Email.class);
71
72     private Properties JavaDoc props;
73
74     private Session JavaDoc session;
75
76     private Store JavaDoc store;
77
78     private Folder JavaDoc folder;
79
80     private Hashtable JavaDoc parameters;
81
82     /**
83      * Email Action
84      *
85      * @author <a HREF="mailto:jlim@gluecode.com">Jonas Lim </a>
86      * @version $Id: Email.java,v 1.2 2004/03/22 22:26:58 taylor Exp $
87      */

88     public Email(String JavaDoc user, String JavaDoc pass, Hashtable JavaDoc param)
89             throws AuthenticationFailedException JavaDoc, NoSuchProviderException JavaDoc,
90             Exception JavaDoc
91     {
92
93         parameters = param;
94         String JavaDoc host = (String JavaDoc) parameters.get("hostname");
95         String JavaDoc protocol = (String JavaDoc) parameters.get("protocol");
96         String JavaDoc smtpUser = (String JavaDoc) parameters.get("smtp_user");
97         String JavaDoc smtpPort = (String JavaDoc) parameters.get("smtp_port");
98         String JavaDoc smtpFrom = (String JavaDoc) parameters.get("smtp_from");
99         String JavaDoc smtpConnTimeout = (String JavaDoc) parameters.get("smtp_conn_timeout");
100         String JavaDoc smptTimeout = (String JavaDoc) parameters.get("smtp_timeout");
101         String JavaDoc smtpLocalhost = (String JavaDoc) parameters.get("smtp_localhost");
102         String JavaDoc smtpEhlo = (String JavaDoc) parameters.get("smtp_ehlo");
103         String JavaDoc smtpAuth = (String JavaDoc) parameters.get("smtp_auth");
104         String JavaDoc smtpDSNNotify = (String JavaDoc) parameters.get("smtp_dsn_notify");
105         String JavaDoc smtpDSNRet = (String JavaDoc) parameters.get("smtp_dsn_ret");
106         String JavaDoc smtpallow8bitmime = (String JavaDoc) parameters
107                 .get("smtp_allow8bitmime");
108         String JavaDoc smtpsendPartial = (String JavaDoc) parameters.get("smtp_send_partial");
109         String JavaDoc smtpSaslrealm = (String JavaDoc) parameters.get("smtp_sasl_realm");
110         String JavaDoc smtpquitWait = (String JavaDoc) parameters.get("smtp_quit_wait");
111         String JavaDoc imapPort = null;
112         String JavaDoc imapPartialfetch = null;
113         String JavaDoc imapFetchsize = null;
114         String JavaDoc imapTimeout = null;
115         String JavaDoc imapHost = null;
116
117         if (protocol.equals("imap"))
118         {
119             imapPort = (String JavaDoc) parameters.get("imap_port");
120             imapPartialfetch = (String JavaDoc) parameters.get("imap_partial_fetch");
121             imapFetchsize = (String JavaDoc) parameters.get("imap_fetch_size");
122             imapTimeout = (String JavaDoc) parameters.get("imap_timeout");
123             imapHost = (String JavaDoc) parameters.get("imap_host");
124         }
125
126         props = new Properties JavaDoc();
127         props.put("mail.smtp.host", host);
128         if (!smtpUser.equals(""))
129         {
130             props.put("mail.smtp.user", smtpUser);
131         }
132         if (!smtpPort.equals(""))
133         {
134             props.put("mail.smtp.port", smtpPort);
135         }
136         if (!smtpFrom.equals(""))
137         {
138             props.put("mail.smtp.from", smtpFrom);
139         }
140         if (!smtpConnTimeout.equals(""))
141         {
142             props.put("mail.smtp.connectiontimeout", smtpConnTimeout);
143         }
144         if (!smptTimeout.equals(""))
145         {
146             props.put("mail.smtp.timeout", smptTimeout);
147         }
148         if (!smtpLocalhost.equals(""))
149         {
150             props.put("mail.smtp.localhost", smtpLocalhost);
151         }
152         if (!smtpEhlo.equals(""))
153         {
154             props.put("mail.smtp.ehlo", smtpEhlo);
155         }
156         if (!smtpAuth.equals(""))
157         {
158             props.put("mail.smtp.auth", smtpAuth);
159         }
160         if (!smtpDSNNotify.equals(""))
161         {
162             props.put("mail.smtp.dsn.notify", smtpDSNNotify);
163         }
164         if (!smtpDSNRet.equals(""))
165         {
166             props.put("mail.smtp.dsn.ret", smtpDSNRet);
167         }
168         if (!smtpallow8bitmime.equals(""))
169         {
170             props.put("mail.smtp.allow8bitmime", smtpallow8bitmime);
171         }
172         if (!smtpsendPartial.equals(""))
173         {
174             props.put("mail.smtp.sendpartial", smtpsendPartial);
175         }
176         if (!smtpSaslrealm.equals(""))
177         {
178             props.put("mail.smtp.saslrealm", smtpSaslrealm);
179         }
180         if (!smtpquitWait.equals(""))
181         {
182             props.put("mail.smtp.quitwait", smtpquitWait);
183         }
184
185         if (protocol.equals("imap"))
186         {
187             if ((imapPort != null) && (!imapPort.equals("")))
188             {
189                 props.put("mail.imap.port", imapPort);
190             }
191             if ((imapPartialfetch != null) && (!imapPartialfetch.equals("")))
192             {
193                 props.put("mail.imap.partialfetch", imapPartialfetch);
194             }
195             if ((imapFetchsize != null) && (!imapFetchsize.equals("")))
196             {
197                 props.put("mail.imap.fetchsize", imapFetchsize);
198             }
199             if ((imapTimeout != null) && (!imapTimeout.equals("")))
200             {
201                 props.put("mail.imap.timeout", imapTimeout);
202             }
203             if ((imapHost != null) && (!imapHost.equals("")))
204             {
205                 props.put("mail.imap.host", imapHost);
206             }
207         }
208         // Get session
209
session = Session.getDefaultInstance(props, null);
210         // Get the store
211
//store = session.getStore("imap");
212
store = session.getStore(protocol);
213         
214
215         store.connect(host, user, pass);
216        // boolean b = store.isConnected();
217
folder = store.getFolder("INBOX");
218
219     }
220
221     public void authenticateUser(String JavaDoc user, String JavaDoc pass)
222             throws AuthenticationFailedException JavaDoc, NoSuchProviderException JavaDoc,
223             Exception JavaDoc
224     {
225         String JavaDoc protocol = (String JavaDoc) parameters.get("protocol");
226         String JavaDoc host = (String JavaDoc) parameters.get("hostname");
227         // Create empty properties
228
Properties JavaDoc props = new Properties JavaDoc();
229         props.put("mail.smtp.host", host);
230
231         // Get session
232
Session JavaDoc session = Session.getDefaultInstance(props, null);
233         // Get the store
234
//Stofalsere store = session.getStore("imap");
235
Store JavaDoc store = session.getStore(protocol);
236         store.connect(host, user, pass);
237
238        
239     }
240
241     public void doSendEmail(String JavaDoc addressTo, String JavaDoc addressFrom,
242             String JavaDoc subject, String JavaDoc msg, FileItem file) throws Exception JavaDoc
243     {
244
245         Session JavaDoc session = Session.getDefaultInstance(props, null);
246         Message JavaDoc message = new MimeMessage JavaDoc(session);
247         message.setFrom(new InternetAddress JavaDoc(addressFrom));
248
249         checkRecipients(addressTo, message);
250
251         // if no subject, default as none
252
if (subject.equals(""))
253         {
254             subject = "none";
255         }
256
257         message.setSubject(subject);
258
259         // Part two is attachment
260
// check if there's an attachment to be sent
261
if (file != null && !file.equals(""))
262         {
263             sendAttachment(message, file, msg);
264         } else
265         {
266             log.info("file null or space " + file);
267             message.setText(msg);
268         }
269
270         Transport.send(message);
271
272         if (file != null)
273         { // delete the file after being uploaded
274
//deleteUploadedfile(file);
275
}
276     }
277
278     public void uploadAttachment(FileItem fileItem) throws Exception JavaDoc
279     {
280
281         log.info("upload attachment");
282         //String contentType = fileItem.getContentType();
283
java.io.File JavaDoc file1 = new java.io.File JavaDoc(fileItem.getFileName());
284
285         String JavaDoc filePath = file1.getAbsolutePath();
286         int d = filePath.lastIndexOf(File.separator);
287         String JavaDoc b = filePath.substring(d + 1);
288         String JavaDoc filename = b;
289
290         fileItem.write(getAttachmentsFolder() + File.separator + filename);
291
292     }
293
294     public void deleteUploadedfile(FileItem file) throws Exception JavaDoc
295     {
296         {
297             log.info("delete uploaded file");
298             java.io.File JavaDoc fn = new java.io.File JavaDoc(file.getFileName());
299             String JavaDoc filename = fn.getName();
300             String JavaDoc realPath = getAttachmentsFolder();
301
302             File JavaDoc fDelete = new File JavaDoc(realPath + File.separator + filename);
303             System.out.println("deleted file : " + fDelete);
304             fDelete.delete();
305         }
306
307     }
308
309     //check if it's a single/multiple recipients
310
public void checkRecipients(String JavaDoc addressTo, Message JavaDoc message)
311             throws Exception JavaDoc
312     {
313         String JavaDoc recipient = null;
314         int startIndex = 0;
315         int semicolonIndex = 0;
316         int lastsemicolonIndex = 0;
317
318         try
319         {
320             if (addressTo.indexOf(";", 0) == -1)
321             {
322                 log.info("addr" + addressTo.indexOf(";", 0));
323                 message.setRecipients(Message.RecipientType.TO, InternetAddress
324                         .parse(addressTo, false));
325             } else
326             {
327                 while ((semicolonIndex = addressTo.indexOf(";", startIndex)) != -1)
328                 {
329                     recipient = addressTo.substring(startIndex, semicolonIndex);
330                     startIndex = semicolonIndex + 1;
331                     lastsemicolonIndex = semicolonIndex;
332                     message.addRecipient(Message.RecipientType.TO,
333                             new InternetAddress JavaDoc(recipient));
334
335                 }
336                 recipient = addressTo.substring(lastsemicolonIndex + 1);
337                 message.addRecipient(Message.RecipientType.TO,
338                         new InternetAddress JavaDoc(recipient));
339                 log.info("recipient" + recipient);
340             }
341             Address JavaDoc a[] = message.getAllRecipients();
342             for (int j = 0; j < a.length; j++)
343             {
344                 log.info("address" + a[j]);
345             }
346
347         } catch (Exception JavaDoc e)
348         {
349             log.error("Error in checkRecepients()",e);
350         }
351     }
352
353     public void sendAttachment(Message JavaDoc message, FileItem file, String JavaDoc msg)
354             throws Exception JavaDoc
355     {
356
357         log.info("file not null or space " + file);
358
359         uploadAttachment(file);
360
361         java.io.File JavaDoc fn = new java.io.File JavaDoc(file.getFileName());
362         String JavaDoc filename = fn.getName();
363
364         //set the message
365
MimeBodyPart JavaDoc messageBodyPart = new MimeBodyPart JavaDoc();
366         //messageBodyPart.setText(msg);
367
messageBodyPart.setContent(msg, "text/html");
368
369         MimeBodyPart JavaDoc messageBodyPart2 = new MimeBodyPart JavaDoc();
370
371         DataSource JavaDoc source = new FileDataSource JavaDoc(getAttachmentsFolder()
372                 + File.separator + filename);
373
374         // Set the data handler to the attachment
375
messageBodyPart2.setDataHandler(new DataHandler JavaDoc(source));
376
377         // Set the filename
378
messageBodyPart2.setFileName(filename.toString());
379
380         // Add the message part and attachment
381
Multipart JavaDoc multipart = new MimeMultipart JavaDoc();
382         multipart.addBodyPart(messageBodyPart);
383         multipart.addBodyPart(messageBodyPart2);
384
385         // Put parts in message
386
message.setContent(multipart);
387
388     }
389
390     public void reply(String JavaDoc from, String JavaDoc addressTo, String JavaDoc msgecontent,
391             String JavaDoc subject, FileItem file, Message JavaDoc msge) throws Exception JavaDoc
392     {
393
394         //since the folder in getMessage method (getting the exact message) is
395
// opened,re-opening the folder may cause an error
396
//folder.open(Folder.READ_ONLY);
397

398         //Message cmessage[] = folder.getMessages();
399
//MimeMessage message = (MimeMessage)msge[current_index].reply(false);
400

401         MimeMessage JavaDoc message = (MimeMessage JavaDoc) msge.reply(false);
402
403         message.setFrom(new InternetAddress JavaDoc(from));
404
405         checkRecipients(addressTo, message);
406
407         message.setSubject(subject);
408
409         message.setContent(msgecontent, "text/html");
410
411         if (file != null && !file.equals(""))
412         {
413             log.info("reply with attachment ******");
414             sendAttachment(message, file, msgecontent);
415         }
416
417         Transport.send(message);
418
419         if (file != null)
420         { // delete the file after being uploaded
421
deleteUploadedfile(file);
422         }
423         //folder.close(true);
424
//store.close();
425

426     }
427
428     public void forward(String JavaDoc to, String JavaDoc from, String JavaDoc subject, String JavaDoc content,
429             Message JavaDoc message) throws Exception JavaDoc
430     {
431
432         //since folder in getMessage method (getting the exact message) is
433
// opened, re-opening the folder may cause an error.
434
//folder.open(Folder.READ_ONLY);
435

436         //Message message[] = folder.getMessages();
437

438         Message JavaDoc forward = new MimeMessage JavaDoc(session);
439
440         forward.setFrom(new InternetAddress JavaDoc(from));
441         forward.setSubject(subject);
442
443         checkRecipients(to, forward);
444
445         MimeMessage JavaDoc orig = (MimeMessage JavaDoc) message;
446         if (orig.isMimeType("text/plain"))
447         {
448             log.info("text/plain forward");
449             forward.setText(content.toString());
450         } else
451         {
452             log.info("forward html *******************");
453             forward.setContent(content, "text/html");
454         }
455
456         Transport.send(forward);
457         //folder.close(true);
458
//store.close();
459
}
460
461     // delete specific message
462
public void contentDelete(int current_index) throws Exception JavaDoc
463     {
464         if(!folder.isOpen())
465         {
466             folder.open(Folder.READ_WRITE);
467         }
468         
469         // Get directory
470
Message JavaDoc message[] = folder.getMessages();
471         message[current_index].setFlag(Flags.Flag.DELETED, true);
472         log.info("index" + current_index);
473     }
474
475     //delete specific message
476
public void contentDelete(int current_index, String JavaDoc foldername,
477             String JavaDoc protocol) throws Exception JavaDoc
478     {
479
480         Folder JavaDoc folder_name = store.getFolder(foldername);
481         folder_name.open(Folder.READ_WRITE);
482         // Get directory
483
Message JavaDoc fmsge[] = folder_name.getMessages();
484         fmsge[current_index].setFlag(Flags.Flag.DELETED, true);
485         if (protocol.equals("imap"))
486         {
487             folder_name.expunge();
488         }
489
490     }
491
492     //multiple delete
493
public void checkboxDelete(String JavaDoc foldername, String JavaDoc[] checkboxes,
494             String JavaDoc protocol) throws Exception JavaDoc
495     {
496         Folder JavaDoc folder_name = store.getFolder(foldername);
497         folder_name.open(Folder.READ_WRITE);
498         // Get directory
499
Message JavaDoc message[] = folder_name.getMessages();
500
501         for (int i = 0; i < checkboxes.length; i++)
502         {
503             int ind = Integer.parseInt(checkboxes[i]);
504             message[ind].setFlag(Flags.Flag.DELETED, true);
505             if (protocol.equals("imap"))
506             {
507                 folder_name.expunge();
508             }
509         }
510     }
511
512     //multiple delete
513
public void checkboxDelete(String JavaDoc[] checkboxes) throws Exception JavaDoc
514     {
515         if(!folder.isOpen())
516         {
517             folder.open(Folder.READ_WRITE);
518         }
519         
520         // Get directory
521
Message JavaDoc message[] = folder.getMessages();
522
523         for (int i = 0; i < checkboxes.length; i++)
524         {
525             int ind = Integer.parseInt(checkboxes[i]);
526             message[ind].setFlag(Flags.Flag.DELETED, true);
527
528         }
529     }
530
531     //get the total no. of messages received
532
public int getNo_of_messages() throws Exception JavaDoc
533     {
534
535         if(!folder.isOpen())
536         {
537             folder.open(Folder.READ_WRITE);
538         }
539         
540         Vector JavaDoc vMessages = new Vector JavaDoc();
541         Message JavaDoc message[] = folder.getMessages();
542
543         int msgectr = message.length;
544         return msgectr;
545
546     }
547
548     // get the total number of new messages
549
public int num_Newmessages() throws Exception JavaDoc
550     {
551
552         if(!folder.isOpen())
553         {
554             folder.open(Folder.READ_ONLY);
555         }
556         
557         
558         Message JavaDoc message[] = folder.getMessages();
559         Vector JavaDoc vNewmessages = new Vector JavaDoc();
560
561         int length = message.length;
562         for (int i = 0; i < length; i++)
563         {
564
565             folder.close(true);
566             Message JavaDoc current_message = getMessage(i);
567             int newMessage = checkNewmessage(current_message);
568             if (newMessage == 1)
569             {
570                 vNewmessages.add(String.valueOf(current_message
571                         .getMessageNumber()));
572                 log.info("@@@@@@@@@@@@@@@@@@@@@@@@@ new!!!");
573             } else
574                 log.info("@@@@@@@@@@@@@@@@@@@@@@@@@ old");
575         }
576         int num_newMessages = vNewmessages.size();
577         return num_newMessages;
578     }
579
580     // this method simply close the inbox folder and store connection...
581
// this is important especially when using pop3 protocol since
582
// pop3 can't re-connect when mailbox is currently used.
583

584     public void close() throws Exception JavaDoc
585     {
586        
587         if(folder.isOpen() && folder != null)
588         {
589             folder.close(true);
590         }
591         
592         if(store.isConnected() && folder != null)
593         {
594             store.close();
595         }
596     }
597
598     public void storeClose() throws Exception JavaDoc
599     {
600         if(store.isConnected() && store != null)
601         {
602             store.close();
603         }
604         
605     }
606
607     public void close(Folder JavaDoc foldername) throws Exception JavaDoc
608     {
609         
610         if(folder.isOpen() && folder != null)
611         {
612             folder.close(true);
613         }
614         
615         if(store.isConnected() && store != null)
616         {
617             store.close();
618         }
619     }
620
621     public Vector JavaDoc openInbox(String JavaDoc protocol) throws Exception JavaDoc
622     {
623
624         if(!folder.isOpen())
625         {
626             folder.open(Folder.READ_ONLY);
627         }
628         
629         Vector JavaDoc vAscmessages = new Vector JavaDoc();
630         Message JavaDoc message[] = folder.getMessages();
631
632         for (int i = 0; i < message.length; i++)
633         {
634
635             Message JavaDoc msge = message[i];
636
637             boolean withAttachment = checkAttachment(msge);
638             Hashtable JavaDoc ht = new Hashtable JavaDoc();
639             ht.put("From", msge.getFrom()[0]);
640             if (msge.getSubject() == null)
641             {
642                 ht.put("Subject", "none"); // set subject to "none" if subject
643
// is null
644
} else
645             {
646                 ht.put("Subject", msge.getSubject());
647             }
648             ht.put("index", String.valueOf(i));
649
650             // POP3 does not provide a "received date", so the getReceivedDate
651
// method will
652
// return null. It may be possible to examine other message headers
653
// (e.g., the "Received" headers) to estimate the received date,
654
// but these techniques are error-prone at best.
655

656             //check protocol... if protocol is pop3, received date is empty
657
if (protocol.equals("imap"))
658             {
659                 ht.put("ReceivedDate", msge.getReceivedDate());
660             } else
661             {
662                 log.info("empty date!!!!!!!");
663                 ht.put("ReceivedDate", "");
664             }
665
666             ht.put("size", String.valueOf(msge.getSize()));
667             ht.put("message", msge);
668             if (withAttachment == true)
669             {
670                 ht.put("hasAttachment", "Attachment");
671             } else
672             {
673                 ht.put("hasAttachment", "");
674             }
675             // check if it's a new message,
676
int status = checkNewmessage(msge);
677             log.info("status " + status);
678
679             if (status == 1)
680             {//new
681
ht.put("status", "new");
682             } else
683             {
684                 ht.put("status", "");
685             }
686             vAscmessages.add(ht);
687         }
688         //folder.close(true); //1-28
689
//store.close(); //1-28
690
return vAscmessages;
691     }
692
693     //get exact message
694
public Message JavaDoc getMessage(int current_index) throws Exception JavaDoc
695     {
696
697         if(!folder.isOpen())
698         {
699             folder.open(Folder.READ_ONLY);
700         }
701         
702         Message JavaDoc[] messages = folder.getMessages();
703         Message JavaDoc message = messages[current_index];
704
705         return message;
706
707     }
708
709     //get the exact message
710
public Message JavaDoc getMessage(int current_index, String JavaDoc foldername)
711             throws Exception JavaDoc
712     {
713
714         Folder JavaDoc folder_name = store.getFolder(foldername);
715         folder_name.open(Folder.READ_ONLY);
716         Message JavaDoc[] messages = folder_name.getMessages();
717         Message JavaDoc message = messages[current_index];
718
719         return message;
720
721     }
722
723     public String JavaDoc getSubject(Message JavaDoc message) throws Exception JavaDoc
724     {
725         //get subject
726
String JavaDoc subject = message.getSubject();
727         return subject;
728     }
729
730     public String JavaDoc getFrom(Message JavaDoc message) throws Exception JavaDoc
731     {
732         String JavaDoc from = message.getFrom()[0].toString();
733         return from;
734     }
735
736     public String JavaDoc getReceivedDate(Message JavaDoc message) throws Exception JavaDoc
737     {
738         String JavaDoc receivedDate = message.getReceivedDate().toString();
739         return receivedDate;
740
741     }
742
743     //get recipients
744
public Vector JavaDoc getTo(Message JavaDoc message) throws Exception JavaDoc
745     {
746         Vector JavaDoc vAddr = new Vector JavaDoc();
747
748         for (int ctr = 0; ctr < message.getRecipients(Message.RecipientType.TO).length; ctr++)
749         {// hcontent.put("To",message[current_index].getRecipients(Message.RecipientType.TO)[ctr]);
750
log.info("allRecipients in showcontent"
751                     + message.getRecipients(Message.RecipientType.TO)[ctr]);
752             vAddr.add(message.getRecipients(Message.RecipientType.TO)[ctr]);
753             log.info("*** all recipients " + vAddr.size());
754         }
755         return vAddr;
756     }
757
758     public String JavaDoc getMessageContent(Message JavaDoc message) throws Exception JavaDoc
759     {
760         String JavaDoc cmessage = null;
761
762         if (message.isMimeType("text/plain"))
763         {
764             //cmessage = convertMessage(message.getContent().toString());
765
cmessage = message.getContent().toString();
766         } else if (message.isMimeType("text/html"))
767         {
768             cmessage = convertMessage(message.getContent().toString());
769         } else
770         {
771             Object JavaDoc obj = message.getContent();
772             Multipart JavaDoc mpart = (Multipart JavaDoc) obj;
773             for (int i = 0, n = mpart.getCount(); i < n; i++)
774             {
775                 Vector JavaDoc vAttachments = new Vector JavaDoc();
776
777                 Part JavaDoc part = mpart.getBodyPart(i);
778                 //get attachment
779
String JavaDoc disposition = part.getDisposition();
780                 if ((disposition != null)
781                         && ((disposition.equalsIgnoreCase(Part.ATTACHMENT)) || (disposition
782                                 .equals(Part.INLINE))))
783                 {
784                     if (disposition.equals(Part.INLINE))
785                     {
786                         if (part.isMimeType("text/plain"))
787                         {
788                             cmessage = (String JavaDoc) part.getContent().toString();
789                         } else
790                         {// if content-type is Image/gif, get the filename and
791
// add to the vector that holds all attachments
792
getAttachments(message);
793                         }
794                     }
795
796                     if (disposition.equalsIgnoreCase(Part.ATTACHMENT))
797                     {
798                         log.info("*** Attachment name: " + part.getFileName());
799                         getAttachments(message);
800                     }
801                 } else if (disposition == null)
802                 {
803                     if (part.getContent() instanceof MimeMultipart JavaDoc)
804                     { // multipart with attachment
805
MimeMultipart JavaDoc mm = (MimeMultipart JavaDoc) part.getContent();
806                         cmessage = (mm.getBodyPart(1)).getContent().toString();
807                     } else
808                     {//multipart - w/o attachment
809
cmessage = (String JavaDoc) part.getContent().toString();
810                     }
811                 }
812             }//for
813
}//else
814
return cmessage;
815     }
816
817     public String JavaDoc getAttachmentname(Message JavaDoc message) throws Exception JavaDoc
818     {
819         Object JavaDoc obj = message.getContent();
820         Multipart JavaDoc mpart = (Multipart JavaDoc) obj;
821         String JavaDoc name = null;
822         for (int i = 0, n = mpart.getCount(); i < n; i++)
823         {
824             Part JavaDoc part = mpart.getBodyPart(i);
825             if (part.getFileName() != null) name = part.getFileName();
826         }
827         return name;
828     }
829
830     public Vector JavaDoc getAttachments(Message JavaDoc message) throws Exception JavaDoc
831     {
832
833         Object JavaDoc obj = message.getContent();
834         Multipart JavaDoc mpart = (Multipart JavaDoc) obj;
835
836         Vector JavaDoc vAtt = new Vector JavaDoc();
837         String JavaDoc name = null;
838         String JavaDoc id = null;
839
840         for (int i = 0, n = mpart.getCount(); i < n; i++)
841         {
842             Part JavaDoc part = mpart.getBodyPart(i);
843             name = part.getFileName();
844
845             if (part.getFileName() != null) vAtt.add(part.getFileName());
846             //attachmentIDs(message);
847
}
848         return vAtt;
849     }
850
851     public boolean checkAttachment(Message JavaDoc message) throws Exception JavaDoc
852     {
853         boolean hasattachment = false;
854         try
855         {
856             if ((message.isMimeType("text/plain"))
857                     || ((message.isMimeType("text/html"))))
858             {
859                 hasattachment = false;
860             }
861
862             else
863             { //multipart
864
Object JavaDoc obj = message.getContent();
865                 Multipart JavaDoc mpart = (Multipart JavaDoc) obj;
866
867                 for (int i = 0, n = mpart.getCount(); i < n; i++)
868                 {
869                     Part JavaDoc part = mpart.getBodyPart(i);
870                     //get attachment
871
String JavaDoc disposition = part.getDisposition();
872
873                     if ((disposition != null)
874                             && ((disposition.equalsIgnoreCase(Part.ATTACHMENT)) || (disposition
875                                     .equals(Part.INLINE))))
876                     {
877                         hasattachment = true;
878                     } else if (disposition == null)
879                     {
880                         if (part.getContent() instanceof MimeMultipart JavaDoc)
881                         {
882                             hasattachment = true;
883                         }
884                     } else
885                         hasattachment = false;
886                 }
887
888                 return hasattachment;
889             }
890         } catch (Exception JavaDoc e)
891         {
892             log.error("Error in checkAttachment",e);
893         }
894         return false;
895     }
896
897     //check if it's a new message
898
public int checkNewmessage(Message JavaDoc message) throws Exception JavaDoc
899     {
900         log.info("### check new message in Email");
901
902         //get message Id to know if it's a new message
903
String JavaDoc msgeId = getMessageId(message);
904
905         Criteria cr = new Criteria();
906         cr.add(EmailInboxPeer.MESSAGE_ID, msgeId);
907         // EmailInbox email =
908
// (EmailInbox)EmailInboxPeer.doSelect(cr).elementAt(0);
909
//Vector vMsge = EmailInboxPeer.doSelect(cr);
910
List JavaDoc vMsge = EmailInboxPeer.doSelect(cr);//tdk2.2 version
911
if (vMsge.isEmpty())
912         { // message id not found in db
913
return 1; // new message
914
} else
915         { // message found in db, flag is set to 0
916
//EmailInbox email =
917
// (EmailInbox)EmailInboxPeer.doSelect(cr).elementAt(0);
918
EmailInbox email = (EmailInbox) EmailInboxPeer.doSelect(cr).get(0);//tdk2.2
919
// version
920
if (email.getReadflag() == 0)
921             {
922                 return 1; // unread message
923
} else
924                 return 0;
925         }
926     }
927
928     /*-----------------------------------------------------------------------------------------*
929      * Retrieves message id from message : RJPY
930      *-----------------------------------------------------------------------------------------*/

931     public String JavaDoc getMessageId(Message JavaDoc message)
932     {
933         String JavaDoc messageid = "";
934         try
935         {
936             // Retrieve message id from headers
937
Enumeration JavaDoc e = message.getAllHeaders();
938             while (messageid.equals(""))
939             {
940                 Header JavaDoc header = (Header JavaDoc) e.nextElement();
941                 if (header.getName().equals("Message-ID"))
942                 {
943                     messageid = header.getValue();
944                 }
945             }
946         } catch (Exception JavaDoc e)
947         {
948             log.error("Error in getMessageId()",e);
949         }
950         return messageid;
951         // end Retrieve
952
}
953
954     public String JavaDoc convertMessage(String JavaDoc msg) throws Exception JavaDoc
955     {
956         log.info("convert message");
957
958         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
959
960         for (int i = 0; i < msg.length(); i++)
961         {
962             char c = msg.charAt(i);
963             if (c == '\n')
964             {
965                 log.info("new line");
966                 sb.append("<br>");
967             } else
968             {
969                 sb.append(c);
970             }
971
972         }
973         String JavaDoc returnString = sb.toString();
974         return returnString;
975     }
976
977     public void doCreatefolder(String JavaDoc folder_name) throws Exception JavaDoc
978     {
979         Folder JavaDoc dfolder = store.getDefaultFolder();
980         //Folder dfolder = store.getFolder("myfolder");
981

982         IMAPFolder newfolder = (IMAPFolder) dfolder.getFolder(folder_name);
983
984         if (newfolder == null)
985         {
986
987             //if the target folder not exist just create it
988
//note:when you create a subfolder you can assign its
989
// attribute.Details,please read the javamail document.
990
}
991
992         if (!newfolder.exists())
993         {
994             //newfolder.create(Folder.HOLDS_FOLDERS);
995
newfolder.create(Folder.HOLDS_MESSAGES);
996         }
997         //allFolders();
998
}
999
1000    public Vector JavaDoc allFolders()
1001    {
1002        Vector JavaDoc vFolders = new Vector JavaDoc();
1003        try
1004        {
1005            Folder JavaDoc allfolders = store.getDefaultFolder();
1006            //Folder allfolders = store.getFolder("myfolder");
1007
Folder JavaDoc[] f = allfolders.list();
1008
1009            for (int i = 0; i < f.length; i++)
1010            {
1011                //String fn = f[i].getFullName();
1012
String JavaDoc fn = f[i].getName();
1013
1014                vFolders.add(fn);
1015            }
1016            //data.getUser().setTemp("vFolders",vFolders);
1017
// data.getSession().setAttribute("vFolders",vFolders);
1018
return vFolders;
1019        } catch (Exception JavaDoc e)
1020        {
1021            log.error("Error in allFolders()",e);
1022            return null;
1023        }
1024    }
1025
1026    public void moveMessage(String JavaDoc fromFolder, String JavaDoc toFolder,
1027            String JavaDoc[] checkboxes)
1028    {
1029        try
1030        {
1031            //get folder destination
1032

1033            //Folder to_folder = store.getFolder("myfolder/"+toFolder);
1034
Folder JavaDoc to_folder = store.getFolder(toFolder);
1035            Folder JavaDoc from_folder = store.getFolder(fromFolder);
1036
1037            from_folder.open(Folder.READ_WRITE);
1038
1039            int tempStart = checkboxes.length;
1040            int startvalue = Integer.parseInt(checkboxes[tempStart - 1]);
1041            int start = startvalue + 1;
1042
1043            int tempEnd = Integer.parseInt(checkboxes[0]);
1044            int end = tempEnd + 1;
1045
1046            to_folder.open(Folder.READ_WRITE);
1047            // get the message
1048
Message JavaDoc msge[] = from_folder.getMessages(start, end);
1049            from_folder.copyMessages(msge, to_folder);
1050            from_folder.close(true);
1051
1052            //delete the message from inbox folder
1053
String JavaDoc protocol = (String JavaDoc) parameters.get("protocol");
1054
1055            checkboxDelete(fromFolder, checkboxes, protocol);
1056
1057        } catch (Exception JavaDoc e)
1058        {
1059            log.error("Error in moveMessage()",e);
1060        }
1061    }
1062
1063    public void moveMessage(String JavaDoc fromFolder, String JavaDoc toFolder,
1064            int current_index)
1065    {
1066        try
1067        {
1068            //get folder destination
1069
//Folder dfolder = store.getFolder("myfolder/"+toFolder);
1070
Folder JavaDoc dfolder = store.getFolder(toFolder);
1071            Folder JavaDoc from_folder = store.getFolder(fromFolder);
1072
1073            from_folder.open(Folder.READ_WRITE);
1074            dfolder.open(Folder.READ_WRITE);
1075
1076            // get the message
1077
Message JavaDoc msge[] = from_folder.getMessages(current_index + 1,
1078                    current_index + 1);
1079            from_folder.copyMessages(msge, dfolder);
1080            //from_folder.close(true);
1081

1082            //delete the message from inbox folder
1083
String JavaDoc protocol = (String JavaDoc) parameters.get("protocol");
1084
1085            contentDelete(current_index, fromFolder, protocol);
1086
1087        } catch (Exception JavaDoc e)
1088        {
1089            log.error("Error in Movemessage()",e);
1090        }
1091
1092    }
1093
1094    public Vector JavaDoc openMyfolder(String JavaDoc foldername, String JavaDoc protocol)
1095            throws Exception JavaDoc
1096    {
1097        Vector JavaDoc message_folder = new Vector JavaDoc();
1098
1099        try
1100        {
1101            Folder JavaDoc fname = store.getFolder(foldername);
1102            fname.open(Folder.READ_ONLY);
1103
1104            Message JavaDoc message[] = fname.getMessages();
1105            for (int i = 0; i < message.length; i++)
1106            {
1107                Message JavaDoc msge = message[i];
1108
1109                boolean withAttachment = checkAttachment(msge);
1110                Hashtable JavaDoc ht = new Hashtable JavaDoc();
1111                ht.put("From", msge.getFrom()[0]);
1112
1113                if (msge.getSubject() == null)
1114                {
1115                    ht.put("Subject", "none"); // set subject to "none" if
1116
// subject is null
1117
} else
1118                {
1119                    ht.put("Subject", msge.getSubject());
1120                }
1121                ht.put("index", String.valueOf(i));
1122
1123                // POP3 does not provide a "received date", so the
1124
// getReceivedDate method will
1125
// return null. It may be possible to examine other message
1126
// headers
1127
// (e.g., the "Received" headers) to estimate the received
1128
// date,
1129
// but these techniques are error-prone at best.
1130

1131                //check protocol... if protocol is pop3, received date is
1132
// empty
1133

1134                if (protocol.equals("imap"))
1135                {
1136                    ht.put("ReceivedDate", msge.getReceivedDate());
1137                } else
1138                {
1139                    log.info("empty date!!!!!!!");
1140                    ht.put("ReceivedDate", "");
1141                }
1142
1143                ht.put("size", String.valueOf(msge.getSize()));
1144                ht.put("message", msge);
1145                if (withAttachment == true)
1146                {
1147                    ht.put("hasAttachment", "Attachment");
1148                } else
1149                {
1150                    ht.put("hasAttachment", "");
1151                }
1152                // check if it's a new message,
1153
int status = checkNewmessage(msge);
1154                log.info("status " + status);
1155
1156                if (status == 1)
1157                {//new
1158
ht.put("status", "new");
1159                } else
1160                {
1161                    ht.put("status", "");
1162                }
1163                message_folder.add(ht);
1164            }
1165            //folder.close(true); //1-28
1166
//store.close(); //1-28
1167
return message_folder;
1168
1169        } catch (Exception JavaDoc e)
1170        {
1171            log.error("Error in openMyFolder()",e);
1172            return message_folder;
1173        }
1174
1175    }
1176
1177    public void folderDelete(String JavaDoc folder_name)
1178    {
1179        try
1180        {
1181            //Folder current_folder =
1182
// store.getFolder("myfolder/"+folder_name);
1183
Folder JavaDoc current_folder = store.getFolder(folder_name);
1184            //current_folder.open(Folder.READ_WRITE);
1185
current_folder.delete(true);
1186
1187        } catch (Exception JavaDoc e)
1188        {
1189            log.error("Error in folderDelete()",e);
1190        }
1191
1192    }
1193
1194    public Folder JavaDoc getFolder(String JavaDoc folder_name)
1195    {
1196        try
1197        {
1198            Folder JavaDoc current_folder = store.getFolder(folder_name);
1199            return current_folder;
1200        } catch (Exception JavaDoc e)
1201        {
1202            log.error("Error in getFolder()",e);
1203            return null;
1204        }
1205    }
1206    
1207    public String JavaDoc getAttachmentsFolder()
1208    {
1209        String JavaDoc path = TurbineServlet.getRealPath(File.separator)
1210                + "attachments";
1211        File JavaDoc aFolder = new File JavaDoc(path);
1212        if (!aFolder.exists())
1213        {
1214            aFolder.mkdir();
1215        }
1216
1217        return path;
1218
1219    }
1220
1221}
Popular Tags