KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > turbine > util > mail > MailMessage


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

18
19 import java.io.UnsupportedEncodingException JavaDoc;
20 import java.util.Enumeration JavaDoc;
21 import java.util.Hashtable JavaDoc;
22 import java.util.Properties JavaDoc;
23 import java.util.StringTokenizer JavaDoc;
24 import java.util.Vector JavaDoc;
25 import javax.mail.Message JavaDoc;
26 import javax.mail.MessagingException JavaDoc;
27 import javax.mail.Session JavaDoc;
28 import javax.mail.Transport JavaDoc;
29 import javax.mail.internet.AddressException JavaDoc;
30 import javax.mail.internet.InternetAddress JavaDoc;
31 import javax.mail.internet.MimeMessage JavaDoc;
32
33 /**
34  * Creates a very simple text/plain message and sends it.
35  *
36  * <p>MailMessage creates a very simple text/plain message and sends
37  * it. It can be used like this:<br>
38  * <pre>
39  * MailMessage sm = new MailMessage("mail.domain.net",
40  * "toYou@domain.net",
41  * "fromMe@domain",
42  * "this is the subject",
43  * "this is the body");
44  * </pre>
45  *
46  * Another example is:<br>
47  * <pre>
48  * MailMessage sm = new MailMessage();
49  * sm.setHost("mail.domain.net");
50  * sm.setHeaders("X-Mailer: Sendmail class, X-Priority: 1(Highest)");
51  * sm.setFrom("Net Freak1 user1@domain.com");
52  * sm.setReplyTo("Net Freak8 user8@domain.com");
53  * sm.setTo("Net Freak2 user2@domain.com, Net Freak3 user3@domain.com");
54  * sm.setCc("Net Freak4 user4@domain.com, Net Freak5 user5@domain.com");
55  * sm.setBcc("Net Freak6 user6@domain.com, Net Freak7 user7@domain.com");
56  * sm.setSubject("New Sendmail Test");
57  * sm.setBody("Test message from Sendmail class, more features to be added.
58  * Like multipart messages, html, binary files...");
59  * sm.setDebug(true);
60  * sm.send();
61  * </pre>
62  *
63  * @author <a HREF="mailto:david@i2a.com">David Duddleston</a>
64  * @version $Id: MailMessage.java,v 1.5.2.2 2004/05/20 03:20:18 seade Exp $
65  * @deprecated Use org.apache.commons.mail.MailMessage instead.
66  */

67 public class MailMessage
68 {
69     /**
70      * The host name of the mail server to use.
71      */

72     protected String JavaDoc host;
73
74     /**
75      * Used to specify the mail headers. Example:
76      *
77      * X-Mailer: Sendmail, X-Priority: 1(highest)
78      * or 2(high) 3(normal) 4(low) and 5(lowest)
79      * Disposition-Notification-To: returnR user@domain.net
80      */

81     protected Hashtable JavaDoc headers;
82
83     /**
84      * The email address that the mail is being sent from.
85      */

86     protected InternetAddress JavaDoc from;
87
88     /**
89      * The email address used for replies to this message.
90      */

91     protected InternetAddress JavaDoc[] replyTo;
92
93     /**
94      * The email address or addresses that the email is being sent to.
95      */

96     protected InternetAddress JavaDoc[] to;
97
98     /**
99      * The email address or addresses that the email is being
100      * carbon-copied to.
101      */

102     protected InternetAddress JavaDoc[] cc;
103
104     /**
105      * The email address or addresses that the email is being
106      * blind-carbon-copied to.
107      */

108     protected InternetAddress JavaDoc[] bcc;
109
110     /**
111      * The subject of the email message.
112      */

113     protected String JavaDoc subject;
114
115     /**
116      * The body of the email message.
117      */

118     protected String JavaDoc body;
119
120     /**
121      * Displays debug information when true.
122      */

123     protected boolean debug;
124
125     /**
126      * Default constructor. Must use the setHost, setTo, and other
127      * set functions to properly send an email. <b>host</b>,
128      * <b>to</b>, <b>cc</b>, <b>bcc</b>, and <b>from</b> are set to
129      * null. <b>subject</b>, and <b>body</b> are set to empty
130      * strings. <b>debug</b> is set to false.
131      */

132     public MailMessage()
133     {
134         this(null, null, null, null, null, "", "", false);
135     }
136
137     /**
138      * Constructor used to specify <b>host</b>, <b>to</b>,
139      * <b>from</b>, <b>subject</b>, and <b>body</b>.
140      *
141      * @param h A String with the host.
142      * @param t A String with the TO.
143      * @param f A String with the FROM.
144      * @param s A String with the SUBJECT.
145      * @param b A String with the BODY.
146      */

147     public MailMessage(String JavaDoc h,
148                        String JavaDoc t,
149                        String JavaDoc f,
150                        String JavaDoc s,
151                        String JavaDoc b)
152     {
153         this(h, t, null, null, f, s, b, false);
154     }
155
156     /**
157      * Constructor used to specify <b>host</b>, <b>to</b>, <b>cc</b>,
158      * <b>bcc</b>, <b>from</b>, <b>subject</b>, <b>body</b>, and
159      * <b>debug</b>.
160      *
161      * @param h A String with the host.
162      * @param t A String with the TO.
163      * @param c A String with the CC.
164      * @param bc A String with the BCC.
165      * @param f A String with the FROM.
166      * @param s A String with the SUBJECT.
167      * @param b A String with the BODY.
168      * @param d True if debugging is wanted.
169      */

170     public MailMessage(String JavaDoc h,
171                        String JavaDoc t,
172                        String JavaDoc c,
173                        String JavaDoc bc,
174                        String JavaDoc f,
175                        String JavaDoc s,
176                        String JavaDoc b,
177                        boolean d)
178     {
179         host = h;
180         to = (t == null ? null : parseAddressField(t));
181         cc = (cc == null ? null : parseAddressField(c));
182         bcc = (bc == null ? null : parseAddressField(bc));
183         from = (f == null ? null : parseInternetAddress(f));
184         subject = s;
185         body = b;
186         debug = d;
187     }
188
189     /**
190      * Adds a header (name, value) to the headers Hashtable.
191      *
192      * @param name A String with the name.
193      * @param value A String with the value.
194      */

195     public void addHeader(String JavaDoc name,
196                           String JavaDoc value)
197     {
198         if (headers == null)
199         {
200             headers = new Hashtable JavaDoc();
201         }
202         headers.put(name, value);
203     }
204
205     /**
206      * Parse an address field.
207      *
208      * @param str A String with the address.
209      * @return An InternetAddress[].
210      */

211     public static InternetAddress JavaDoc[] parseAddressField(String JavaDoc str)
212     {
213         String JavaDoc[] addressList;
214         if (str.indexOf(",") != -1)
215         {
216             Vector JavaDoc v = new Vector JavaDoc();
217             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(str, ",", false);
218             while (st.hasMoreTokens())
219             {
220                 v.addElement(st.nextToken());
221             }
222             addressList = new String JavaDoc[v.size()];
223             for (int i = 0; i < v.size(); i++)
224             {
225                 addressList[i] = (String JavaDoc) v.elementAt(i);
226             }
227         }
228         else
229         {
230             addressList = new String JavaDoc[1];
231             addressList[0] = str;
232         }
233         return parseAddressList(addressList);
234     }
235
236     /**
237      * Parse an address list.
238      *
239      * @param aList A String[] with the addresses.
240      * @return An InternetAddress[].
241      */

242     public static InternetAddress JavaDoc[] parseAddressList(String JavaDoc[] aList)
243     {
244         InternetAddress JavaDoc[] ia = new InternetAddress JavaDoc[aList.length];
245
246         for (int i = 0; i < aList.length; i++)
247         {
248             ia[i] = parseInternetAddress(aList[i]);
249         }
250
251         return ia;
252
253     }
254
255     /**
256      * Parse a header.
257      *
258      * @param str A String with the header.
259      * @param headers A Hashtable with the current headers.
260      */

261     public static void parseHeader(String JavaDoc str,
262                                    Hashtable JavaDoc headers)
263     {
264         String JavaDoc name = null;
265         String JavaDoc value = null;
266
267         str = str.trim();
268         int sp = str.lastIndexOf(":");
269         name = str.substring(0, sp);
270         value = (str.substring(sp + 1)).trim();
271
272         headers.put(name, value);
273     }
274
275     /**
276      * Parse a header field.
277      *
278      * @param str A String with the header field.
279      * @return A Hashtable with the parsed headers.
280      */

281     public static Hashtable JavaDoc parseHeaderField(String JavaDoc str)
282     {
283         String JavaDoc[] headerList;
284         if (str.indexOf(",") != -1)
285         {
286             Vector JavaDoc v = new Vector JavaDoc();
287             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(str, ",", false);
288             while (st.hasMoreTokens())
289             {
290                 v.addElement(st.nextToken());
291             }
292             headerList = new String JavaDoc[v.size()];
293             for (int i = 0; i < v.size(); i++)
294             {
295                 headerList[i] = (String JavaDoc) v.elementAt(i);
296             }
297         }
298         else
299         {
300             headerList = new String JavaDoc[1];
301             headerList[0] = str;
302         }
303         return parseHeaderList(headerList);
304     }
305
306     /**
307      * Parse a header list.
308      *
309      * @param hList A String[] with the headers.
310      * @return A Hashtable with the parsed headers.
311      */

312     public static Hashtable JavaDoc parseHeaderList(String JavaDoc[] hList)
313     {
314         Hashtable JavaDoc headers = new Hashtable JavaDoc();
315
316         for (int i = 0; i < hList.length; i++)
317         {
318             // headers.put("one", new Integer(1));
319
parseHeader(hList[i], headers);
320         }
321
322         return headers;
323     }
324
325     /**
326      * Parse an Internet address.
327      *
328      * @param str A String with the address.
329      * @return An InternetAddress.
330      */

331     public static InternetAddress JavaDoc parseInternetAddress(String JavaDoc str)
332     {
333         String JavaDoc address = null;
334         String JavaDoc personal = null;
335
336         str = str.trim();
337         if (str.indexOf(" ") == -1)
338         {
339             address = str;
340         }
341         else
342         {
343             int sp = str.lastIndexOf(" ");
344             address = str.substring(sp + 1);
345             personal = str.substring(0, sp);
346         }
347         return parseInternetAddress(address, personal);
348     }
349
350     /**
351      * Parse an Internet address.
352      *
353      * @param address A String with the address.
354      * @param personal A String.
355      * @return An InternetAddress.
356      */

357     public static InternetAddress JavaDoc parseInternetAddress(String JavaDoc address,
358                                                        String JavaDoc personal)
359     {
360         InternetAddress JavaDoc ia = null;
361         try
362         {
363             ia = new InternetAddress JavaDoc(address);
364
365             if (personal != null)
366             {
367                 ia.setPersonal(personal);
368             }
369         }
370         catch (AddressException JavaDoc e)
371         {
372             e.printStackTrace();
373             System.out.println();
374         }
375         catch (UnsupportedEncodingException JavaDoc e)
376         {
377             e.printStackTrace();
378             System.out.println();
379         }
380
381         return ia;
382     }
383
384     /**
385      * Send the message. The to, from, subject, host, and body should
386      * be set prior to using this method.
387      *
388      * @return True is message was sent.
389      */

390     public boolean send()
391     {
392         // Create some properties and get the default Session.
393
Properties JavaDoc props = new Properties JavaDoc();
394         props.put("mail.smtp.host", host);
395
396         Session JavaDoc session = Session.getInstance(props, null);
397         session.setDebug(debug);
398
399         try
400         {
401             // Create a message.
402
Message JavaDoc msg = new MimeMessage JavaDoc(session);
403
404             // Set the email address that the message is from.
405
msg.setFrom(from);
406
407             // Set the email addresses that the message is to.
408
msg.setRecipients(Message.RecipientType.TO, to);
409
410             // Set the email addresses that will be carbon-copied.
411
if (cc != null)
412             {
413                 msg.setRecipients(Message.RecipientType.CC, cc);
414             }
415
416             // Set the email addresses that will be
417
// blind-carbon-copied.
418
if (bcc != null)
419             {
420                 msg.setRecipients(Message.RecipientType.BCC, bcc);
421             }
422
423             // Set the email addresses that reply-to messages are
424
// sent.
425
if (replyTo != null)
426             {
427                 msg.setReplyTo(replyTo);
428             }
429
430             // Set the subject of the email message.
431
msg.setSubject(subject);
432
433             // Set the body of the message. If the desired charset is
434
// known, use setText(text, charset).
435
msg.setText(body);
436
437             // msg.addHeader("X-Mailer", "com.i2a.util.mail.Sendmail");
438

439             if (headers != null)
440             {
441                 Enumeration JavaDoc e = headers.keys();
442                 while (e.hasMoreElements())
443                 {
444                     String JavaDoc name = (String JavaDoc) e.nextElement();
445                     String JavaDoc value = (String JavaDoc) headers.get(name);
446                     msg.addHeader(name, value);
447                 }
448             }
449
450             // Send the message.
451
Transport.send(msg);
452         }
453         catch (MessagingException JavaDoc mex)
454         {
455             mex.printStackTrace();
456             Exception JavaDoc ex = null;
457             if ((ex = mex.getNextException()) != null)
458             {
459                 ex.printStackTrace();
460             }
461             return false;
462         }
463         return true;
464     }
465
466     /**
467      * Used to specify the email address that the mail is being
468      * blind-carbon-copied to.
469      *
470      * @param bc An InternetAddress[].
471      */

472     public void setBcc(InternetAddress JavaDoc[] bc)
473     {
474         bcc = bc;
475     }
476
477     /**
478      * Used to specify the email address that the mail is being
479      * blind-carbon-copied to.
480      *
481      * @param bc A String.
482      */

483     public void setBcc(String JavaDoc bc)
484     {
485         bcc = parseAddressField(bc);
486     }
487
488     /**
489      * Used to specify the body of the email message.
490      *
491      * @param b A String.
492      */

493     public void setBody(String JavaDoc b)
494     {
495         body = b;
496     }
497
498     /**
499      * Used to specify the email address that the mail is being sent
500      * to.
501      *
502      * @param c An InternetAddress[].
503      */

504     public void setCc(InternetAddress JavaDoc[] c)
505     {
506         cc = c;
507     }
508
509     /**
510      * Used to specify the email address that the mail is being
511      * carbon-copied to.
512      *
513      * @param c A String.
514      */

515     public void setCc(String JavaDoc c)
516     {
517         cc = parseAddressField(c);
518     }
519
520     /**
521      * Setting to true will enable the display of debug information.
522      *
523      * @param str A String.
524      */

525     public void setDebug(String JavaDoc str)
526     {
527         if (str.equals("1"))
528         {
529             debug = true;
530         }
531         else if (str.equals("0"))
532         {
533             debug = false;
534         }
535         else
536         {
537             debug = new Boolean JavaDoc(str).booleanValue();
538         }
539     }
540
541     /**
542      * Setting to true will enable the display of debug information.
543      *
544      * @param d A boolean.
545      */

546     public void setDebug(boolean d)
547     {
548         debug = d;
549     }
550
551     /**
552      * Used to specify the email address that the mail is being sent
553      * from.
554      *
555      * @param f A String.
556      */

557     public void setFrom(String JavaDoc f)
558     {
559         from = parseInternetAddress(f);
560     }
561
562     /**
563      * Used to specify the email address that the mail is being sent
564      * from.
565      *
566      * @param f An InternetAddress.
567      */

568     public void setFrom(InternetAddress JavaDoc f)
569     {
570         from = f;
571     }
572
573     /**
574      * Used to specify the mail headers. Example:
575      *
576      * X-Mailer: Sendmail, X-Priority: 1(highest)
577      * or 2(high) 3(normal) 4(low) and 5(lowest)
578      * Disposition-Notification-To: returnR user@domain.net
579      *
580      * @param h A String.
581      */

582     public void setHeaders(String JavaDoc h)
583     {
584         headers = parseHeaderField(h);
585     }
586
587     /**
588      * Used to specify the mail headers. Example:
589      *
590      * X-Mailer: Sendmail, X-Priority: 1(highest)
591      * or 2(high) 3(normal) 4(low) and 5(lowest)
592      * Disposition-Notification-To: returnR user@domain.net
593      *
594      * @param h A Hashtable.
595      */

596     public void setHeaders(Hashtable JavaDoc h)
597     {
598         headers = h;
599     }
600
601     /**
602      * Used to specify the mail server host.
603      *
604      * @param h A String.
605      */

606     public void setHost(String JavaDoc h)
607     {
608         host = h;
609     }
610
611     /**
612      * Used to specify the email address that the mail is being sent
613      * from.
614      *
615      * @param rt An InternetAddress[].
616      */

617     public void setReplyTo(InternetAddress JavaDoc[] rt)
618     {
619         replyTo = rt;
620     }
621
622     /**
623      * Used to specify the email address that the mail is being sent
624      * from.
625      *
626      * @param rp A String.
627      */

628     public void setReplyTo(String JavaDoc rp)
629     {
630         replyTo = parseAddressField(rp);
631     }
632
633     /**
634      * Used to specify the subject of the email message.
635      *
636      * @param s A String.
637      */

638     public void setSubject(String JavaDoc s)
639     {
640         subject = s;
641     }
642
643     /**
644      * Used to specify the email address that the mail is being sent
645      * to.
646      *
647      * @param t An InternetAddress[].
648      */

649     public void setTo(InternetAddress JavaDoc[] t)
650     {
651         to = t;
652     }
653
654     /**
655      * Used to specify the email address that the mail is being sent
656      * to.
657      *
658      * @param t A String.
659      */

660     public void setTo(String JavaDoc t)
661     {
662         to = parseAddressField(t);
663     }
664 }
665
Popular Tags