KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > micronova > util > MailTransport


1 /*
2
3 Copyright 2003-2007 MicroNova (R)
4 All rights reserved.
5
6 Redistribution and use in source and binary forms, with or
7 without modification, are permitted provided that the following
8 conditions are met:
9
10     * Redistributions of source code must retain the above copyright
11     notice, this list of conditions and the following disclaimer.
12
13     * Redistributions in binary form must reproduce the above copyright
14     notice, this list of conditions and the following disclaimer in the
15     documentation and/or other materials provided with the distribution.
16
17     * Neither the name of MicroNova nor the names of its contributors
18     may be used to endorse or promote products derived from this
19     software without specific prior written permission.
20
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
25 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 POSSIBILITY OF SUCH DAMAGE.
32
33 */

34
35
36 package com.micronova.util;
37
38 import java.util.*;
39 import java.io.*;
40 import java.net.*;
41
42 import javax.mail.*;
43 import javax.mail.internet.*;
44 import javax.activation.*;
45
46 /** Simple Map-based mail support. An instance of this is internally used as an javax.mail.Authenticator. */
47
48 public class MailTransport extends javax.mail.Authenticator JavaDoc
49 {
50     /** methods for internal use as an Authenticator */
51
52     protected String JavaDoc user;
53     protected String JavaDoc password;
54     
55     protected MailTransport(String JavaDoc user, String JavaDoc password)
56     {
57         super();
58         this.user = user;
59         this.password = password;
60     }
61     
62     protected javax.mail.PasswordAuthentication JavaDoc getPasswordAuthentication()
63     {
64         return new javax.mail.PasswordAuthentication JavaDoc(user, password);
65     }
66
67     /** Returns a new mail session. */
68
69     public static Session getSession(Properties properties, URLName urlName)
70     {
71         String JavaDoc protocol = urlName.getProtocol();
72         String JavaDoc host = urlName.getHost();
73         int port = urlName.getPort();
74
75         if (protocol != null)
76         {
77             properties.setProperty("mail.transport.protocol", protocol);
78             
79             if (host != null)
80             {
81                 properties.setProperty("mail." + protocol + ".host", host);
82                 properties.setProperty("mail.host", host);
83             }
84             
85             if (port >= 0)
86             {
87                 properties.setProperty("mail." + protocol + ".port", Integer.toString(port));
88             }
89         }
90
91         String JavaDoc user = urlName.getUsername();
92         
93         if (user == null)
94         {
95             user = properties.getProperty("mail." + protocol + ".user");
96         }
97         else
98         {
99             properties.setProperty("mail." + protocol + ".user", user);
100         }
101         
102         String JavaDoc password = urlName.getPassword();
103         
104         if (password == null)
105         {
106             password = properties.getProperty("mail." + protocol + ".password");
107         }
108         else
109         {
110             properties.setProperty("mail." + protocol + ".password", password);
111         }
112         
113         if ((user != null) && (password != null))
114         {
115             properties.setProperty("mail." + protocol + ".auth", "true");
116         }
117         
118         if ((user != null) && (password != null))
119         {
120             return Session.getInstance(properties, new MailTransport(user, password));
121         }
122         else
123         {
124             return Session.getInstance(properties);
125         }
126     }
127
128     public static final String JavaDoc URL = "url";
129
130     public static final String JavaDoc TO = "to";
131     public static final String JavaDoc CC = "cc";
132     public static final String JavaDoc BCC= "bcc";
133     public static final String JavaDoc FROM = "from";
134     public static final String JavaDoc REPLYTO = "replyTo";
135
136     public static final String JavaDoc SUBJECT = "subject";
137     public static final String JavaDoc TYPE = "type";
138     public static final String JavaDoc SENTDATE = "sentDate";
139
140     public static final String JavaDoc HEADER = "header";
141     public static final String JavaDoc FILENAME = "fileName";
142     public static final String JavaDoc DATASOURCE = "dataSource";
143     public static final String JavaDoc CONTENT = "content";
144
145     /** make internet address from an object */
146
147     protected static InternetAddress makeAddress(Object JavaDoc object) throws Exception JavaDoc
148     {
149         if (object instanceof InternetAddress)
150         {
151             return (InternetAddress)object;
152         }
153         else if (object instanceof Map)
154         {
155             Map map = (Map)object;
156
157             String JavaDoc address = (String JavaDoc)map.get("address");
158             String JavaDoc personal = (String JavaDoc)map.get("personal");
159             String JavaDoc charset = (String JavaDoc)map.get("charset");
160
161             return new InternetAddress(address, personal, charset);
162         }
163         else
164         {
165             return new InternetAddress((String JavaDoc)object);
166         }
167     }
168
169     /** get address list */
170
171     protected static List getAddressList(Object JavaDoc object)
172     {
173         if (object == null)
174         {
175             return null;
176         }
177         else if (object instanceof NestedMap)
178         {
179             return ((NestedMap)object).getSubList(false);
180         }
181         else
182         {
183             List list = TypeUtil.isList(object);
184
185             if (list == null)
186             {
187                 list = StringUtil.split(object.toString(), ',');
188             }
189
190             return list;
191         }
192     }
193
194     /** sets addresses of a message. object can be either comma-separated list of addresses, List or array of String or Address */
195
196     protected static void setAddress(Message message, String JavaDoc type, Object JavaDoc object) throws Exception JavaDoc
197     {
198         List list = getAddressList(object);
199                 
200         if (list != null)
201         {
202             int listSize = list.size();
203
204             Address[] addresses = null;
205
206             if (listSize > 0)
207             {
208                 addresses = new Address[listSize];
209             
210                 for (int i = listSize; --i >= 0;)
211                 {
212                     addresses[i] = makeAddress(list.get(i));
213                 }
214             }
215
216             if (type == REPLYTO)
217             {
218                 message.setReplyTo(addresses);
219             }
220             else if (type == FROM)
221             {
222                 message.setFrom(null);
223                 message.addFrom(addresses);
224             }
225             else if (type == TO)
226             {
227                 message.setRecipients(Message.RecipientType.TO, addresses);
228             }
229             else if (type == CC)
230             {
231                 message.setRecipients(Message.RecipientType.CC, addresses);
232             }
233             else if (type == BCC)
234             {
235                 message.setRecipients(Message.RecipientType.BCC, addresses);
236             }
237         }
238     }
239
240     /** set replyTo or from */
241
242     public static void setReplyTo(MimeMessage message, String JavaDoc type, Object JavaDoc object) throws Exception JavaDoc
243     {
244         List list = getAddressList(object);
245             
246         if (list != null)
247         {
248             int listSize = list.size();
249             
250             Address[] addresses = new Address[listSize];
251             
252             for (int i = listSize; --i >= 0;)
253             {
254                 Object JavaDoc listItem = list.get(i);
255
256                 InternetAddress address = makeAddress(listItem);
257
258                 addresses[i] = address;
259             }
260
261             
262             message.setReplyTo(addresses);
263         }
264     }
265
266     /** set sentDate */
267
268     public static void setSentDate(MimeMessage message, Object JavaDoc date) throws Exception JavaDoc
269     {
270         if (date != null)
271         {
272             if (date instanceof Date)
273             {
274                 message.setSentDate((Date)date);
275             }
276             else
277             {
278                 Long JavaDoc longDate = TypeUtil.isLong(date);
279
280                 if (longDate != null)
281                 {
282                     message.setSentDate(new Date(longDate.longValue()));
283                 }
284             }
285         }
286     }
287
288     /** build message parts */
289
290     public static void buildPart(MimePart part, NestedMap map) throws Exception JavaDoc
291     {
292         NestedMap headerMap = (NestedMap)map.get(HEADER);
293
294         if (headerMap != null)
295         {
296             List list = headerMap.getSubList(false);
297
298             if (list != null)
299             {
300                 Iterator iterator = list.iterator();
301
302                 while (iterator.hasNext())
303                 {
304                     Object JavaDoc header = iterator.next();
305
306                     if (header instanceof Map)
307                     {
308                         String JavaDoc name = (String JavaDoc)(((Map)header).get("name"));
309                         String JavaDoc value = (String JavaDoc)(((Map)header).get("value"));
310
311                         if ((name != null) && (value != null))
312                         {
313                             part.addHeader(name, value);
314                         }
315                     }
316                     else if (header instanceof String JavaDoc)
317                     {
318                         part.addHeaderLine(header.toString());
319                     }
320                 }
321             }
322
323             Iterator iterator = headerMap.entrySet().iterator();
324
325             while (iterator.hasNext())
326             {
327                 Map.Entry entry = (Map.Entry)iterator.next();
328                 
329                 Object JavaDoc key = entry.getKey();
330                 Object JavaDoc value = entry.getValue();
331                 
332                 if (value != list)
333                 {
334                     part.setHeader(key.toString(), value.toString());
335                 }
336             }
337         }
338         
339         Object JavaDoc typeObject = map.get(TYPE);
340         
341         List list = map.getSubList(false);
342
343         if ((list == null) || (list.isEmpty()))
344         {
345             String JavaDoc content = TypeUtil.isString(map.get(CONTENT));
346
347             if (content == null)
348             {
349                 content = "";
350             }
351
352             String JavaDoc type = null;
353        
354             if (typeObject != null)
355             {
356                 if (typeObject instanceof Map)
357                 {
358                     type = NetUtil.encodeMime((Map)typeObject);
359                 }
360                 else if (typeObject instanceof String JavaDoc)
361                 {
362                     type = (String JavaDoc)typeObject;
363                 }
364             }
365
366             if (content != null)
367             {
368                 String JavaDoc typeString = (type != null) ? type : "text/plain; charset=iso-8859-1";
369                 String JavaDoc fileName = map.getString(FILENAME);
370
371                 ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(typeString, fileName, content.getBytes("iso-8859-1"));
372
373                 part.setDataHandler(new DataHandler(byteArrayDataSource));
374             }
375
376             Object JavaDoc dataSource = map.get(DATASOURCE);
377
378             if (dataSource != null)
379             {
380                 if (dataSource instanceof DataSource)
381                 {
382                     part.setDataHandler(new DataHandler((DataSource)dataSource));
383                 }
384                 else
385                 {
386                     URL url = new URL(dataSource.toString());
387
388                     part.setDataHandler(new DataHandler(new URLDataSource(url)));
389                     part.setFileName(map.getString(FILENAME, url.getFile().replaceAll("/?[^/]*/", "")));
390                 }
391
392                 if (type != null)
393                 {
394                     part.setHeader("Content-Type", type);
395                 }
396             }
397         }
398         else
399         {
400             MimeMultipart mp = new MimeMultipart();
401
402             String JavaDoc type = "related";
403
404             if (typeObject instanceof Map)
405             {
406                 type = (String JavaDoc)((Map)typeObject).get(NetUtil.MIMESUBTYPE);
407             }
408             else
409             {
410                 type = (String JavaDoc)typeObject;
411             }
412             
413             mp.setSubType(type);
414
415             Iterator iterator = list.iterator();
416
417             while (iterator.hasNext())
418             {
419                 NestedMap subMap = (NestedMap)iterator.next();
420
421                 MimeBodyPart bodyPart = new MimeBodyPart();
422
423                 buildPart(bodyPart, subMap);
424
425                 mp.addBodyPart(bodyPart);
426             }
427
428             part.setContent(mp);
429         }
430     }
431
432     /** send map-based email */
433
434     public static void send(Session session, Transport transport, NestedMap map) throws Exception JavaDoc
435     {
436         MimeMessage message = new MimeMessage(session);
437
438         buildPart(message, map);
439
440         String JavaDoc subject = map.getString(SUBJECT, "");
441
442         message.setSubject(subject);
443
444         setAddress(message, TO, map.get(TO));
445         setAddress(message, CC, map.get(CC));
446         setAddress(message, BCC, map.get(BCC));
447         setAddress(message, REPLYTO, map.get(REPLYTO));
448         setAddress(message, FROM, map.get(FROM));
449         
450         setSentDate(message, map.get(SENTDATE));
451         
452         transport.send(message);
453     }
454 }
455
Popular Tags