KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > commons > net > Email


1 /*
2  * The contents of this file are subject to the
3  * Mozilla Public License Version 1.1 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS IS"
8  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
9  * See the License for the specific language governing rights and
10  * limitations under the License.
11  *
12  * The Initial Developer of the Original Code is Simulacra Media Ltd.
13  * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
14  *
15  * All Rights Reserved.
16  *
17  * Contributor(s):
18  */

19 package org.openharmonise.commons.net;
20
21 import java.io.*;
22 import java.util.logging.*;
23 import java.util.logging.Level JavaDoc;
24
25 import javax.activation.*;
26 import javax.mail.Multipart JavaDoc;
27 import javax.mail.internet.*;
28
29
30 /**
31  *
32  * A convenience class to simplify the process of sending an email using
33  * the JavaMail API.
34  *
35  * @version $Revision: 1.2 $
36  *
37  */

38 public class Email extends Object JavaDoc {
39     
40     /**
41      * Plain text mime type
42      */

43     public static final String JavaDoc CTYPE_TXTPLAIN = "text/plain";
44     
45     /**
46      * HTML mime type
47      */

48     public static final String JavaDoc CTYPE_HTML = "text/html";
49     
50     /**
51      * Email importance header
52      */

53     protected static final String JavaDoc HEADER_IMPORTANCE = "Importance";
54     
55     /**
56      * Email importance header value of 'high'
57      */

58     public static final String JavaDoc IMPORTANCE_HIGH = "High";
59     
60     /**
61      * <code>boolean</code> flag indicating whether email has an attachment
62      */

63     private static boolean m_bAttachment = false;
64     
65     /**
66      * Importance header value
67      */

68     protected String JavaDoc m_sImportance = null;
69     
70     /**
71      * Email 'to' address
72      */

73     protected String JavaDoc to_address;
74     
75     /**
76      * Email 'from' address
77      */

78     protected String JavaDoc from_address;
79     
80     /**
81      * Email message text
82      */

83     protected String JavaDoc message_text;
84     
85     /**
86      * Email subject text
87      */

88     protected String JavaDoc subject_text;
89     
90     /**
91      * Email message mime type.
92      */

93     protected String JavaDoc message_contenttype = CTYPE_TXTPLAIN;
94     
95     /**
96      * Mail host for email.
97      */

98     protected String JavaDoc m_sMailhost = "";
99     
100     /**
101      * Attachment file.
102      */

103     protected File m_fAttachment = null;
104     
105     /**
106      * Logger for this class.
107      */

108     private static final Logger m_logger = Logger.getLogger(Email.class.getName());
109
110     /**
111     * The constructor allows you to create an email object. The object is then filled with all the information about the email, ie sender, reciever, subject and the actual message.
112     * The Email constructor does NOT send the message until the send method is called.
113     *
114     * @param mailhost - the mailhost to be used for email
115     * @param to_address - The email address of the RECIEVER , example: Mellon@yahoo.com
116     * @param from_address - The email address of the SENDER , example: Orange@hotmail.com
117     * @param subject_text - What the subject of the message is about
118     * @param message_text - The actual content of the message
119     */

120     public Email(String JavaDoc mailhost,String JavaDoc to_address, String JavaDoc from_address, String JavaDoc subject_text,
121                  String JavaDoc message_text) {
122         this.to_address = to_address;
123         this.from_address = from_address;
124         this.subject_text = subject_text;
125         this.message_text = message_text;
126         m_sMailhost = mailhost;
127     }
128
129     /**
130     * The constructor allows you to create an email object. The object is then filled with all the information about the email, ie sender, reciever, subject and the actual message.
131     * The Email constructor does NOT send the message until the send method is called.
132     *
133     * @param mailhost - the mailhost to be used for email
134     * @param to_address - The email address of the RECIEVER , example: Mellon@yahoo.com
135     * @param from_address - The email address of the SENDER , example: Orange@hotmail.com
136     * @param subject_text - What the subject of the message is about
137     * @param message_text - The actual content of the message
138     */

139     public Email(String JavaDoc mailhost,String JavaDoc to_address, String JavaDoc from_address, String JavaDoc subject_text,
140                  String JavaDoc message_text, File attachment)
141           throws Exception JavaDoc {
142         this.to_address = to_address;
143         this.from_address = from_address;
144         this.subject_text = subject_text;
145         this.message_text = message_text;
146         m_fAttachment = attachment;
147         m_bAttachment = true;
148         m_sMailhost = mailhost;
149     }
150
151     /**
152     * This method will send all of the email details specified earlier
153     * when the email object was constructed.
154     * @return boolean - to say whether the msg was sent, or not.
155     */

156     public boolean send() {
157         try {
158             // create some properties and get the default Session
159
java.util.Properties JavaDoc props = new java.util.Properties JavaDoc();
160             String JavaDoc mail_host = m_sMailhost;
161             props.put("mail.smtp.host", mail_host);
162
163             javax.mail.Session JavaDoc session = javax.mail.Session.getInstance(props);
164
165             if (!m_bAttachment) {
166                 javax.mail.Message JavaDoc msg = new javax.mail.internet.MimeMessage JavaDoc(
167                                                  session);
168
169                 if (m_sImportance != null) {
170                     msg.setHeader(HEADER_IMPORTANCE, m_sImportance);
171                 }
172
173                 msg.setFrom(
174                         new javax.mail.internet.InternetAddress JavaDoc(from_address));
175
176                 msg.setRecipient(javax.mail.Message.RecipientType.TO,
177                                  new javax.mail.internet.InternetAddress JavaDoc(
178                                          to_address));
179                 msg.setSubject(subject_text);
180                 msg.setSentDate(new java.util.Date JavaDoc());
181
182
183                 msg.setContent(message_text, message_contenttype);
184
185                 javax.mail.Transport.send(msg);
186             } else {
187                 // Define message from this session
188
MimeMessage msg = new MimeMessage(session);
189
190                 if (m_sImportance != null) {
191                     msg.setHeader(HEADER_IMPORTANCE, m_sImportance);
192                 }
193
194                 msg.setFrom(
195                         new javax.mail.internet.InternetAddress JavaDoc(from_address));
196
197                 msg.setRecipient(javax.mail.Message.RecipientType.TO,
198                                  new javax.mail.internet.InternetAddress JavaDoc(
199                                          to_address));
200
201
202                 // set what the subject of this mail is about
203
msg.setSubject(subject_text);
204
205                 // create the messageBodypart , Its an object that is done in parts
206
// the mail text, and the attachments, these form the whole message
207
MimeBodyPart messageBodyPart = new MimeBodyPart();
208
209
210                 //**** Part one - Add the text to the email
211
//fill message (with the text)
212
messageBodyPart.setText(message_text);
213
214                 // create a mulipart object of which to compose the whole email from
215
// Think of it as some sort of email object VECTOR
216
// the first part to add is the message
217
Multipart JavaDoc multipart = new MimeMultipart();
218
219
220                 // add the text to the mutipart object
221
multipart.addBodyPart(messageBodyPart);
222
223                 //**** Part two is attachment (ie the file)
224
// reinitialise the messageBodyPart object
225
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
226
227                 // get the data source(ie attachment path)
228
FileDataSource source = new FileDataSource(this.m_fAttachment);
229
230
231                 //FileDataSource source = new FileDataSource(fileAttachment);
232
messageBodyPart2.setDataHandler(new DataHandler(source));
233
234
235                 // set the name of the attachment
236
messageBodyPart2.setFileName(source.getName());
237
238
239                 // add the message body part to the mulipart (or email)
240
multipart.addBodyPart(messageBodyPart2);
241
242
243                 // Put the msg content to be the multipart to form the complete email
244
// dont forget that the multipart object by now should contain the text of the email as well as
245
// the attachment file
246
msg.setContent(multipart);
247
248
249                 // send the email
250
javax.mail.Transport.send(msg);
251             }
252         } catch (Exception JavaDoc e) {
253             
254             return false;
255         }
256
257         return true;
258     }
259
260     /**
261      * Debug method which will build a description of steps executed during
262      * the emailing process.
263      *
264      * @return description of process
265      */

266     public String JavaDoc testSend() {
267         StringWriter sw = new StringWriter();
268         PrintWriter err_out = new PrintWriter(sw);
269
270         try {
271             // create some properties and get the default Session
272
java.util.Properties JavaDoc props = new java.util.Properties JavaDoc();
273             String JavaDoc mail_host = m_sMailhost;
274             err_out.println("Using mail_host:" + mail_host + "<br>");
275
276             props.put("mail.smtp.host", mail_host);
277
278             javax.mail.Session JavaDoc session = javax.mail.Session.getDefaultInstance(
279                                                  props, null);
280             err_out.println("created mail session:" + props + "<br>");
281
282             try {
283                 // create a message
284
javax.mail.Message JavaDoc msg = new javax.mail.internet.MimeMessage JavaDoc(
285                                                  session);
286                 err_out.println("created mail msg:" + msg + "<br>");
287
288                 msg.setFrom(
289                         new javax.mail.internet.InternetAddress JavaDoc(from_address));
290                 err_out.println("setFrom:" + from_address + "<br>");
291
292                 msg.setRecipient(javax.mail.Message.RecipientType.TO,
293                                  new javax.mail.internet.InternetAddress JavaDoc(
294                                          to_address));
295                 err_out.println("setRecipient:" + to_address + "<br>");
296
297                 msg.setSubject(subject_text);
298                 err_out.println("setSubject:" + subject_text + "<br>");
299
300                 msg.setSentDate(new java.util.Date JavaDoc());
301                 err_out.println("setSentDate." + "<br>");
302
303
304                 msg.setContent(message_text, message_contenttype);
305
306                 err_out.println("setText:" + message_text + "<br>");
307                 err_out.println("setContent:" + message_contenttype + "<br>");
308
309                 javax.mail.Transport.send(msg);
310                 err_out.println("sent mail." + "<br>");
311             } catch (javax.mail.MessagingException JavaDoc mex) {
312                 err_out.println("\n--Exception handling for mail" + "<br>");
313
314                 m_logger.log(Level.WARNING, mex.getLocalizedMessage(), mex);
315
316                 Exception JavaDoc ex = mex;
317
318                 do {
319                     if (ex instanceof javax.mail.SendFailedException JavaDoc) {
320                         javax.mail.SendFailedException JavaDoc sfex =
321                                 (javax.mail.SendFailedException JavaDoc) ex;
322                         javax.mail.Address JavaDoc[] invalid =
323                                 sfex.getInvalidAddresses();
324
325                         if (invalid != null) {
326                             err_out.println(" ** Invalid Addresses" +
327                                             "<br>");
328
329                             if (invalid != null) {
330                                 for (int i = 0; i < invalid.length; i++)
331                                     err_out.println(" " + invalid[i] +
332                                                     "<br>");
333                             }
334                         }
335
336                         javax.mail.Address JavaDoc[] validUnsent =
337                                 sfex.getValidUnsentAddresses();
338
339                         if (validUnsent != null) {
340                             err_out.println(" ** ValidUnsent Addresses" +
341                                             "<br>");
342
343                             if (validUnsent != null) {
344                                 for (int i = 0; i < validUnsent.length; i++)
345                                     err_out.println(" " +
346                                                     validUnsent[i] + "<br>");
347                             }
348                         }
349
350                         javax.mail.Address JavaDoc[] validSent =
351                                 sfex.getValidSentAddresses();
352
353                         if (validSent != null) {
354                             err_out.println(" ** ValidSent Addresses" +
355                                             "<br>");
356
357                             if (validSent != null) {
358                                 for (int i = 0; i < validSent.length; i++)
359                                     err_out.println(" " +
360                                                     validSent[i] + "<br>");
361                             }
362                         }
363                     }
364
365                     err_out.println("<br>");
366                 } while ((ex = ((javax.mail.MessagingException JavaDoc) ex).getNextException()) != null);
367             }
368         }
369         catch (Exception JavaDoc e) {
370             err_out.println("Exception sending mail:" + e.getMessage() +
371                             "<br>");
372             err_out.println();
373             err_out.println("Stacktrace follows:" + "<br>");
374             e.printStackTrace(err_out);
375         }
376         finally {
377             if (err_out != null) {
378                 err_out.close();
379             }
380         }
381         
382         return sw.toString();
383     }
384
385     /**
386     * This method will change the email Address of where the message is GOING.
387     * ie to who the message is being SENT.
388     *
389     * @param new_email_address the address of where the email is going : example mellon2@yahoo.com
390     */

391     public void SetEmailAddress(String JavaDoc new_email_address) {
392         this.to_address = new_email_address;
393
394         return;
395     }
396
397     /**
398     * This method will change the content type.
399     */

400     public void SetContentType(String JavaDoc content_type) {
401         content_type = content_type.trim();
402
403         if (content_type.equals(Email.CTYPE_HTML) ||
404                 content_type.equals(Email.CTYPE_TXTPLAIN)) {
405             this.message_contenttype = content_type;
406         } else {
407             throw new RuntimeException JavaDoc("Cannot set content type to:" +
408                                        content_type +
409                                        ", allowed values are:" + CTYPE_HTML +
410                                        " " + CTYPE_TXTPLAIN);
411         }
412     }
413
414     /**
415      * Sets the importance heading of the email.
416      *
417      * @param sImportance
418      */

419     public void setImportance(String JavaDoc sImportance) {
420         m_sImportance = sImportance;
421     }
422 }
Popular Tags