KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lucane > applications > jmail > base > MailClient


1 package org.lucane.applications.jmail.base;
2
3 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
4  * This file is part of JMail *
5  * Copyright (C) 2002-2003 Yvan Norsa <norsay@wanadoo.fr> *
6  * *
7  * JMail is free software; you can redistribute it and/or modify *
8  * it under the terms of the GNU General Public License as published by *
9  * the Free Software Foundation; either version 2 of the License, or *
10  * any later version. *
11  * *
12  * JMail is distributed in the hope that it will be useful, *
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15  * GNU General Public License for more details. *
16  * *
17  * You should have received a copy of the GNU General Public License along *
18  * with JMail; if not, write to the Free Software Foundation, Inc., *
19  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20  * *
21  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

22
23 import java.io.*;
24 import java.util.*;
25 import javax.activation.*;
26 import javax.mail.*;
27 import javax.mail.internet.*;
28 import javax.swing.*;
29 import javax.swing.tree.*;
30
31 import org.lucane.client.widgets.DialogBox;
32
33 /** Class allowing to interact with mail servers */
34 final class MailClient
35 {
36     /**
37      * Makes the connection to the mail server
38      * @param profile user profile
39      * @return the connection
40      */

41     protected final static Store connect(Profile profile)
42     {
43         try {
44             // Get OS's parameters
45
Properties props = System.getProperties();
46
47             // This is the trick to get SSL working.. Thanks to Maximilian Schwerin
48
// ( http://jaymail.sourceforge.net/ )
49
if (profile.getUseSSL())
50                 props.setProperty("mail.imap.socketFactory.class", "JMailSSLSocketFactory");
51             else
52             {
53                 // because an IMAP/POP connection without SSL would fail if the prop is set
54
// FIXME : it seems tough to prevent further non-SSL connections to check mails
55
// every three minutes :-\
56
props.remove("mail.imap.socketFactory.class");
57             }
58
59             Session s = Session.getInstance(props);
60             //s.setDebug(false);
61

62             /** Connection */
63             Store store = s.getStore(profile.getType());
64             store.connect(profile.getIncoming(), profile.getIncomingPort(),
65                 profile.getLogin(), profile.getDecryptedMailPassword());
66
67             return store;
68         } catch(Exception JavaDoc e) {
69             DialogBox.error("" + e);
70             e.printStackTrace();
71             return null;
72         }
73     }
74
75     /**
76      * Get folders names
77      * @param store the connection
78      * @param profile user profile
79      * @return tree showing folders
80      */

81     protected final static JTree getFolders(Store store, Profile profile)
82     {
83         DefaultMutableTreeNode top;
84
85         top = new DefaultMutableTreeNode("Mailbox");
86         DefaultTreeModel model = new DefaultTreeModel(top);
87
88         try {
89             if (profile.getType().compareTo("pop3") == 0)
90                 top.add(new DefaultMutableTreeNode(store.getFolder("INBOX").getFullName()));
91             else //if(profile.getType().compareTo("imap") == 0)
92
{
93                 //add default folders first if available
94
try {
95                     top.add(getFolder(store.getFolder("INBOX")));
96                 } catch(Exception JavaDoc e) {}
97                 try {
98                     top.add(getFolder(store.getFolder("Sent")));
99                 } catch(Exception JavaDoc e) {}
100                 try {
101                     top.add(getFolder(store.getFolder("Drafts")));
102                 } catch(Exception JavaDoc e) {}
103                 try {
104                     top.add(getFolder(store.getFolder("Trash")));
105                 } catch(Exception JavaDoc e) {}
106
107                 //add user defined folders
108
Folder folder = store.getDefaultFolder();
109                 if(folder != null)
110                 {
111                     TreeNode node = getFolder(folder);
112                     for(int i=0;i<node.getChildCount();i++)
113                     {
114                         DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i);
115                         if(!alreadyHasFolder(top, (String JavaDoc)child.getUserObject()))
116                             top.add((MutableTreeNode)node.getChildAt(i));
117                     }
118                 }
119             }
120
121             return new JTree(model);
122         } catch (Exception JavaDoc e) {
123             DialogBox.error("" + e);
124             e.printStackTrace();
125             return null;
126         }
127     }
128
129     /**
130      * Recursive function to browse folders
131      * @param f base folder
132      * @return sub-tree
133      */

134     private static DefaultMutableTreeNode getFolder(Folder f)
135     {
136         try {
137             //TODO check if this doesn't break anything to change this
138
//DefaultMutableTreeNode node = new DefaultMutableTreeNode(f.getName());
139
DefaultMutableTreeNode node = new DefaultMutableTreeNode(f.getFullName());
140             
141             Folder sons[] = f.listSubscribed();
142
143             if (sons != null)
144             {
145                 for (int i = 0; i < sons.length; i++)
146                 {
147                     if(!alreadyHasFolder(node, sons[i].getFullName()))
148                         node.add(getFolder(sons[i]));
149                 }
150             }
151             return node;
152         } catch (Exception JavaDoc e) {
153             return null;
154         }
155     }
156
157
158     private static boolean alreadyHasFolder(DefaultMutableTreeNode node, String JavaDoc folder)
159     {
160         if(node.getChildCount() > 0)
161         {
162             DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getFirstChild();
163             while(child != null)
164             {
165                 if(child.getUserObject().equals(folder))
166                     return true;
167             
168                 child = child.getNextSibling();
169             }
170         }
171         return false;
172     }
173
174     /**
175      * Delete a mail on the server
176      * @param store the connection
177      * @param currentFolder folder holding the mail
178      * @param id mail-to-delete's id
179      * @return boolean saying wether the operation succeded or not
180      */

181     protected final static boolean deleteMessage(Store store, Folder currentFolder, String JavaDoc id)
182     {
183         try {
184             // Get the messages
185
Message msg[] = currentFolder.getMessages();
186             String JavaDoc currentId = null;
187
188             for(int i = 0; i < msg.length; i++)
189             {
190                 currentId = ((MimeMessage) msg[i]).getMessageID();
191
192                 if(currentId != null)
193                 {
194                     // If we have found the mail to delete
195
if (currentId.compareTo(id) == 0)
196                     {
197                         // Set the flag
198
msg[i].setFlag(Flags.Flag.DELETED, true);
199                         break;
200                     }
201                 }
202             }
203
204             return true;
205         } catch (Exception JavaDoc e) {
206             DialogBox.error("" + e);
207             e.printStackTrace();
208             return false;
209         }
210     }
211
212     /**
213      * Copy a mail from a folder to another
214      * @param store the connection
215      * @param currentFolder folder holding the mail
216      * @param id mail-to-copy's id
217      * @param dest destination folder
218      * @return boolean saying wether the operation succeded
219      */

220     protected final static boolean copyMsg(Store store, Folder currentFolder, String JavaDoc id, String JavaDoc dest)
221     {
222         try {
223             // Get the messages
224
Message msg[] = currentFolder.getMessages();
225
226             // Array which will get the mail
227
Message moved[] = new Message[1];
228
229             int i;
230             String JavaDoc currentId = null;
231
232             for(i=0; i<msg.length; i++)
233             {
234                 currentId = ((MimeMessage) msg[i]).getMessageID();
235                 if(currentId != null)
236                 {
237                     if(currentId.compareTo(id) == 0)
238                     {
239                         // We copy the mail
240
moved[0] = msg[i];
241                         break;
242                     }
243                 }
244             }
245
246             // Open the destinatory folder
247
Folder f2 = store.getFolder(dest);
248             f2.open(Folder.READ_WRITE);
249             currentFolder.copyMessages(moved, f2);
250             f2.close(false);
251
252             return true;
253         } catch (Exception JavaDoc e) {
254             DialogBox.error("" + e);
255             e.printStackTrace();
256             return false;
257         }
258     }
259
260     /**
261      * Move a mail from a folder to another
262      * @param store the connection
263      * @param currentFolder folder containing the mail
264      * @param id mail-to-move's id
265      * @param dest destinatory target
266      * @return boolean saying wether the operation has succeded
267      */

268     protected final static boolean moveMsg(Store store, Folder currentFolder, String JavaDoc id, String JavaDoc dest)
269     {
270         try {
271             // Get the messages
272
Message msg[] = currentFolder.getMessages();
273
274             // Array for the mail to move
275
Message moved[] = new Message[1];
276
277             int i;
278             String JavaDoc currentId = null;
279
280             for(i=0;i<msg.length;i++)
281             {
282                 currentId = ((MimeMessage) msg[i]).getMessageID();
283
284                 if(currentId != null)
285                 {
286                     if(((MimeMessage) msg[i]).getMessageID().compareTo(id) == 0)
287                     {
288                         // We copy the mail
289
moved[0] = msg[i];
290                         break;
291                     }
292                 }
293             }
294
295             Folder f2 = store.getFolder(dest);
296             if (!f2.isOpen())
297                 f2.open(Folder.READ_WRITE);
298             f2.appendMessages(moved);
299             f2.close(false);
300
301             msg[i].setFlag(Flags.Flag.DELETED, true);
302
303             return true;
304         } catch (Exception JavaDoc e) {
305             DialogBox.error("" + e);
306             e.printStackTrace();
307             return false;
308         }
309     }
310
311     /**
312      * Delete a mail folder
313      * @param currentFolder folder to delete
314      * @return boolean telling wether the operation succeeded or not
315      */

316     protected final static boolean deleteFolder(Folder currentFolder)
317     {
318         try {
319             if (currentFolder.isOpen())
320                 currentFolder.close(true);
321             return currentFolder.delete(true);
322         } catch (Exception JavaDoc e) {
323             DialogBox.error("" + e);
324             e.printStackTrace();
325             return false;
326         }
327     }
328
329     /**
330      * Allows to create a folder on the mail server
331      * @param store the connection
332      * @param profile user profile
333      * @param name name of the folder
334      * @param type type of the folder (see <code>Folder</code>)
335      */

336     protected final static void createFolder(Store store, Profile profile, String JavaDoc name, int type)
337     {
338         try {
339             Folder f = store.getFolder(name);
340             f.create(type);
341             f.setSubscribed(true);
342         } catch (Exception JavaDoc e) {
343             DialogBox.error("" + e);
344             e.printStackTrace();
345         }
346     }
347
348     /**
349      * Sends a mail
350      * @param dest the TO field
351      * @param cc the CC field
352      * @param bcc the BCC field
353      * @param subject subject of the mail
354      * @param content body of the message
355      * @param filenames attached files
356      * @param profile user profile
357      * @return a boolean telling wether the mail was succesfully sent or not
358      */

359     protected final static boolean sendMsg(String JavaDoc dest[], String JavaDoc cc[], String JavaDoc bcc[],
360         String JavaDoc subject, String JavaDoc content, Vector filenames, Profile profile)
361     {
362         try {
363             // Set the SMTP server
364
Properties p = System.getProperties();
365             p.put("mail.smtp.host", profile.getOutgoing());
366
367             // Get the OS's parameters
368
Session s = Session.getInstance(System.getProperties());
369
370             InternetAddress addr[] = new InternetAddress[dest.length];
371             for (int i = 0; i < addr.length; i++)
372                 addr[i] = new InternetAddress(dest[i]);
373
374             InternetAddress addrCC[] = new InternetAddress[cc.length];
375             for (int i = 0; i < cc.length; i++)
376                 addrCC[i] = new InternetAddress(cc[i]);
377
378             InternetAddress addrBCC[] = new InternetAddress[bcc.length];
379             for (int i = 0; i < addrBCC.length; i++)
380                 addrBCC[i] = new InternetAddress(bcc[i]);
381
382             InternetAddress a = new InternetAddress(profile.getEmail());
383             Message m = new MimeMessage(s);
384             m.setHeader("X-Mailer", "JMail " + Common.JMAIL_VERSION);
385
386             String JavaDoc replyTo = profile.getReplyTo();
387             if (replyTo != null && replyTo.compareTo("") != 0)
388                 m.setHeader("Reply-To", replyTo);
389
390             m.setFrom(a);
391             m.setRecipients(Message.RecipientType.TO, addr);
392             m.setRecipients(Message.RecipientType.CC, addrCC);
393             m.setRecipients(Message.RecipientType.BCC, addrBCC);
394             m.setSubject(subject);
395
396             int size = filenames.size();
397             if (size == 0)
398                 m.setText(content);
399             else
400             {
401                 MimeMultipart mp = new MimeMultipart();
402                 MimeBodyPart bp1 = new MimeBodyPart();
403                 bp1.setContent(content, "text/plain");
404                 mp.addBodyPart(bp1);
405                 
406                 MimeBodyPart parts[] = new MimeBodyPart[size];
407                 String JavaDoc name = null;
408                 File f = null;
409                 String JavaDoc shortName = null;
410
411                 for(int i=0; i<size; i++)
412                 {
413                     parts[i] = new MimeBodyPart();
414                     name = (String JavaDoc) filenames.get(i);
415                     f = new File(name);
416                     shortName = f.getName();
417                     parts[i].setFileName(shortName);
418                     parts[i].setContent(shortName, "text/plain");
419                     parts[i].setDataHandler(new DataHandler(new FileDataSource(f)));
420                     mp.addBodyPart(parts[i]);
421                 }
422
423                 m.setContent(mp);
424             }
425
426             Transport t = s.getTransport(new URLName("smtp://" + profile.getOutgoing()));
427             t.connect(profile.getOutgoing(), profile.getOutgoingPort(), profile.getLogin(), profile.getPassword());
428             Transport.send(m);
429             t.close();
430         } catch (Exception JavaDoc e) {
431             DialogBox.error("" + e);
432             e.printStackTrace();
433             return false;
434         }
435         
436         return true;
437     }
438 }
439
Popular Tags