KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dspace > core > Email


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

40 package org.dspace.core;
41
42 import java.io.File JavaDoc;
43 import java.text.MessageFormat JavaDoc;
44 import java.util.ArrayList JavaDoc;
45 import java.util.Date JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.Properties JavaDoc;
49
50 import javax.activation.DataHandler JavaDoc;
51 import javax.activation.FileDataSource JavaDoc;
52 import javax.mail.Address JavaDoc;
53 import javax.mail.Authenticator JavaDoc;
54 import javax.mail.BodyPart JavaDoc;
55 import javax.mail.Message JavaDoc;
56 import javax.mail.MessagingException JavaDoc;
57 import javax.mail.Multipart JavaDoc;
58 import javax.mail.PasswordAuthentication JavaDoc;
59 import javax.mail.Session JavaDoc;
60 import javax.mail.Transport JavaDoc;
61 import javax.mail.internet.InternetAddress JavaDoc;
62 import javax.mail.internet.MimeBodyPart JavaDoc;
63 import javax.mail.internet.MimeMessage JavaDoc;
64 import javax.mail.internet.MimeMultipart JavaDoc;
65
66 /**
67  * Class representing an e-mail message, also used to send e-mails.
68  * <P>
69  * Typical use:
70  * <P>
71  * <code>Email email = ConfigurationManager.getEmail(name);</code><br>
72  * <code>email.addRecipient("foo@bar.com");</code><br>
73  * <code>email.addArgument("John");</code><br>
74  * <code>email.addArgument("On the Testing of DSpace");</code><br>
75  * <code>email.send();</code><br>
76  * <P>
77  * <code>name</code> is the name of an email template in
78  * <code>dspace-dir/config/emails/</code> (which also includes the subject.)
79  * <code>arg0</code> and <code>arg1</code> are arguments to fill out the
80  * message with.
81  * <P>
82  * Emails are formatted using <code>java.text.MessageFormat.</code>
83  * Additionally, comment lines (starting with '#') are stripped, and if a line
84  * starts with "Subject:" the text on the right of the colon is used for the
85  * subject line. For example:
86  * <P>
87  *
88  * <pre>
89  *
90  * # This is a comment line which is stripped
91  * #
92  * # Parameters: {0} is a person's name
93  * # {1} is the name of a submission
94  * #
95  * Subject: Example e-mail
96  *
97  * Dear {0},
98  *
99  * Thank you for sending us your submission &quot;{1}&quot;.
100  *
101  * </pre>
102  *
103  * <P>
104  * If the example code above was used to send this mail, the resulting mail
105  * would have the subject <code>Example e-mail</code> and the body would be:
106  * <P>
107  *
108  * <pre>
109  *
110  *
111  * Dear John,
112  *
113  * Thank you for sending us your submission &quot;On the Testing of DSpace&quot;.
114  *
115  * </pre>
116  *
117  * <P>
118  * Note that parameters like <code>{0}</code> cannot be placed in the subject
119  * of the e-mail; they won't get filled out.
120  *
121  *
122  * @author Robert Tansley
123  * @author Jim Downing - added attachment handling code
124  * @version $Revision: 1.10 $
125  */

126 public class Email
127 {
128     /*
129      * Implementation note: It might be necessary to add a quick utility method
130      * like "send(to, subject, message)". We'll see how far we get without it -
131      * having all emails as templates in the config allows customisation and
132      * internationalisation.
133      *
134      * Note that everything is stored and the run in send() so that only send()
135      * throws a MessagingException.
136      */

137
138     /** The content of the message */
139     private String JavaDoc content;
140
141     /** The subject of the message */
142     private String JavaDoc subject;
143
144     /** The arguments to fill out */
145     private List JavaDoc arguments;
146
147     /** The recipients */
148     private List JavaDoc recipients;
149
150     /** Reply to field, if any */
151     private String JavaDoc replyTo;
152
153     private List JavaDoc attachments;
154
155     /**
156      * Create a new email message.
157      */

158     Email()
159     {
160         arguments = new ArrayList JavaDoc(50);
161         recipients = new ArrayList JavaDoc(50);
162         attachments = new ArrayList JavaDoc(10);
163         subject = "";
164         content = "";
165         replyTo = null;
166     }
167
168     /**
169      * Add a recipient
170      *
171      * @param email
172      * the recipient's email address
173      */

174     public void addRecipient(String JavaDoc email)
175     {
176         recipients.add(email);
177     }
178
179     /**
180      * Set the content of the message. Setting this "resets" the message
181      * formatting -<code>addArgument</code> will start. Comments and any
182      * "Subject:" line must be stripped.
183      *
184      * @param cnt
185      * the content of the message
186      */

187     void setContent(String JavaDoc cnt)
188     {
189         content = cnt;
190         arguments = new ArrayList JavaDoc();
191     }
192
193     /**
194      * Set the subject of the message
195      *
196      * @param s
197      * the subject of the message
198      */

199     void setSubject(String JavaDoc s)
200     {
201         subject = s;
202     }
203
204     /**
205      * Set the reply-to email address
206      *
207      * @param email
208      * the reply-to email address
209      */

210     public void setReplyTo(String JavaDoc email)
211     {
212         replyTo = email;
213     }
214
215     /**
216      * Fill out the next argument in the template
217      *
218      * @param arg
219      * the value for the next argument
220      */

221     public void addArgument(Object JavaDoc arg)
222     {
223         arguments.add(arg);
224     }
225
226     public void addAttachment(File JavaDoc f, String JavaDoc name)
227     {
228         attachments.add(new FileAttachment(f, name));
229     }
230
231     /**
232      * "Reset" the message. Clears the arguments and recipients, but leaves the
233      * subject and content intact.
234      */

235     public void reset()
236     {
237         arguments = new ArrayList JavaDoc(50);
238         recipients = new ArrayList JavaDoc(50);
239         attachments = new ArrayList JavaDoc(10);
240         replyTo = null;
241     }
242
243     /**
244      * Sends the email.
245      *
246      * @throws MessagingException
247      * if there was a problem sending the mail.
248      */

249     public void send() throws MessagingException JavaDoc
250     {
251         // Get the mail configuration properties
252
String JavaDoc server = ConfigurationManager.getProperty("mail.server");
253         String JavaDoc from = ConfigurationManager.getProperty("mail.from.address");
254
255         // Set up properties for mail session
256
Properties JavaDoc props = System.getProperties();
257         props.put("mail.smtp.host", server);
258
259         // Get session
260
Session JavaDoc session;
261         
262         // Get the SMTP server authentication information
263
String JavaDoc username = ConfigurationManager.getProperty("mail.server.username");
264         String JavaDoc password = ConfigurationManager.getProperty("mail.server.password");
265         
266         if (username != null)
267         {
268             props.put("mail.smtp.auth", "true");
269             SMTPAuthenticator smtpAuthenticator = new SMTPAuthenticator(
270                     username, password);
271             session = Session.getDefaultInstance(props, smtpAuthenticator);
272         }
273         else
274         {
275             session = Session.getDefaultInstance(props);
276         }
277
278         // Create message
279
MimeMessage JavaDoc message = new MimeMessage JavaDoc(session);
280
281         // Set the recipients of the message
282
Iterator JavaDoc i = recipients.iterator();
283
284         while (i.hasNext())
285         {
286             message.addRecipient(Message.RecipientType.TO, new InternetAddress JavaDoc(
287                     (String JavaDoc) i.next()));
288         }
289
290         // Format the mail message
291
Object JavaDoc[] args = arguments.toArray();
292         String JavaDoc fullMessage = MessageFormat.format(content, args);
293         Date JavaDoc date = new Date JavaDoc();
294
295         message.setSentDate(date);
296         message.setFrom(new InternetAddress JavaDoc(from));
297         message.setSubject(subject);
298         if (attachments.isEmpty())
299         {
300             message.setText(fullMessage);
301         }
302         else
303         {
304             Multipart JavaDoc multipart = new MimeMultipart JavaDoc();
305             // create the first part of the email
306
BodyPart JavaDoc messageBodyPart = new MimeBodyPart JavaDoc();
307             messageBodyPart.setText(fullMessage);
308             multipart.addBodyPart(messageBodyPart);
309
310             for (Iterator JavaDoc iter = attachments.iterator(); iter.hasNext();)
311             {
312                 FileAttachment f = (FileAttachment) iter.next();
313                 // add the file
314
messageBodyPart = new MimeBodyPart JavaDoc();
315                 messageBodyPart.setDataHandler(new DataHandler JavaDoc(
316                         new FileDataSource JavaDoc(f.file)));
317                 messageBodyPart.setFileName(f.name);
318                 multipart.addBodyPart(messageBodyPart);
319             }
320             message.setContent(multipart);
321         }
322
323         if (replyTo != null)
324         {
325             Address JavaDoc[] replyToAddr = new Address JavaDoc[1];
326             replyToAddr[0] = new InternetAddress JavaDoc(replyTo);
327             message.setReplyTo(replyToAddr);
328         }
329
330         Transport.send(message);
331     }
332
333     /**
334      * Utility struct class for handling file attachments.
335      *
336      * @author ojd20
337      *
338      */

339     private class FileAttachment
340     {
341         public FileAttachment(File JavaDoc f, String JavaDoc n)
342         {
343             this.file = f;
344             this.name = n;
345         }
346
347         File JavaDoc file;
348
349         String JavaDoc name;
350     }
351     
352     /**
353      * Inner Class for SMTP authentication information
354      */

355     private class SMTPAuthenticator extends Authenticator JavaDoc
356     {
357         // User name
358
private String JavaDoc name;
359         
360         // Password
361
private String JavaDoc password;
362         
363         public SMTPAuthenticator(String JavaDoc n, String JavaDoc p)
364         {
365             name = n;
366             password = p;
367         }
368         
369         protected PasswordAuthentication JavaDoc getPasswordAuthentication()
370         {
371             return new PasswordAuthentication JavaDoc(name, password);
372         }
373     }
374 }
375
Popular Tags