KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > mail > MailService


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12

13 package org.jahia.services.mail;
14
15 import java.io.PrintWriter JavaDoc;
16 import java.io.StringWriter JavaDoc;
17 import java.util.Date JavaDoc;
18 import java.util.Properties JavaDoc;
19
20 import javax.mail.Message JavaDoc;
21 import javax.mail.Multipart JavaDoc;
22 import javax.mail.Session JavaDoc;
23 import javax.mail.Transport JavaDoc;
24 import javax.mail.internet.InternetAddress JavaDoc;
25 import javax.mail.internet.MimeMessage JavaDoc;
26
27 import org.jahia.bin.JahiaInterface;
28 import org.jahia.exceptions.JahiaException;
29 import org.jahia.services.JahiaInitializableService;
30 import org.jahia.settings.SettingsBean;
31
32 /**
33  * <p>Title: </p>
34  * <p>Description:
35  * This service define method to send e-mails.
36  * </p>
37  * <p>Copyright: MAP (Jahia Solutions Sàrl 2003)</p>
38  * <p>Company: Jahia Solutions Sàrl</p>
39  * LOQUTUS PATCH : Added sendMail method which allows the use of a Multipart object for the email body
40  * @author MAP
41  * @version 1.0
42  */

43 public class MailService extends JahiaInitializableService {
44
45     /**
46      * Returns the singleton instance of the service, and creates it if there
47      * wasn't one.
48      * @return a MailService object that is the singleton instance of
49      * this service.
50      * @throws JahiaException not used for the moment but reserved for later
51      * use.
52      */

53     public static synchronized MailService getInstance()
54             throws JahiaException {
55         if (singletonInstance == null) {
56             singletonInstance = new MailService();
57         }
58         return singletonInstance;
59     }
60
61     /**
62      * Implementation of the JahiaInitializableService. (For future purposes)
63      *
64      * @param jSettings Jahia Private Settings
65      */

66     public void init(SettingsBean jSettings) {
67         logger.debug("Start Mail Service");
68         this.to = jSettings.mail_administrator;
69         if (this.to == null) {
70             this.to = null;
71         }
72         this.from = jSettings.mail_from;
73         if (this.from == null) {
74             this.from = null;
75         }
76         this.mailhost = jSettings.mail_server;
77         if (this.mailhost.equals("") || to.equals("") || from.equals("")) {
78             logger.warn("Mail settings not valid, ignoring...");
79         }
80         if (this.mailhost == null || to == null || from == null) {
81             logger.warn("Mail settings not valid, ignoring...");
82         }
83         logger.debug("Using default settings mailhost=[" + this.mailhost +
84                      "] to=[" + to + "] from=[" + from + "]");
85     }
86
87     /**
88      * Send message to the default Jahia settings defined in the jahia.properties
89      * file.
90      *
91      * @param message The message to send
92      * @return True if message is sent successfully, false otherwise
93      */

94     public boolean sendMessage(String JavaDoc message) {
95         return sendMessage(this.from, this.to, null, null,
96                 this.subject, this.mailhost, message, false);
97     }
98     
99     /**
100      * Send message to the desired destination.
101      *
102      * @param to The message destination.
103      * @param message The message to send.
104      * @return True if message is sent successfully, false otherwise
105      */

106     public boolean sendMessage(String JavaDoc to, String JavaDoc message) {
107         return sendMessage(this.from, to, null, null,
108                            this.subject, this.mailhost, message, false);
109     }
110
111     /**
112      * Send message to the desired destination.
113      *
114      * @param from The message sender
115      * @param to The message destination.
116      * @param message The message to send.
117      * @return True if message is sent successfully, false otherwise
118      */

119     public boolean sendMessage(String JavaDoc from, String JavaDoc to, String JavaDoc message) {
120         return sendMessage(from, to, null, null,
121                            this.subject, this.mailhost, message, false);
122     }
123
124     /**
125      * Send message to the desired destination with cc and bcc option. The
126      * subject can also be mentionned.
127      *
128      * @param from The message sender
129      * @param to The message destination.
130      * @param cc The message copy destination.
131      * @param bcc The message copy blind destination.
132      * @param subject The message subject.
133      * @param message The message to send.
134      * @return True if message is sent successfully, false otherwise
135      */

136     public boolean sendMessage(String JavaDoc from, String JavaDoc to, String JavaDoc cc, String JavaDoc bcc,
137                                String JavaDoc subject, String JavaDoc message) {
138         return sendMessage(from, to, cc, bcc,
139                            subject, this.mailhost, message, false);
140     }
141     
142     /**
143      * Send message to the desired destination with cc and bcc option. The
144      * subject can also be mentionned.
145      *
146      * @param from The message sender
147      * @param to The message destination.
148      * @param cc The message copy destination.
149      * @param bcc The message copy blind destination.
150      * @param subject The message subject.
151      * @param message The message to send.
152      * @param htmlFormat true if message MIME type is text/html, false if message is plain text *
153      * @return True if message is sent successfully, false otherwise
154      */

155     public boolean sendMessage(String JavaDoc from, String JavaDoc to, String JavaDoc cc, String JavaDoc bcc,
156                                String JavaDoc subject, String JavaDoc message, boolean htmlFormat) {
157         return sendMessage(from, to, cc, bcc,
158                            subject, this.mailhost, message, htmlFormat);
159     }
160
161     /**
162      * Send message to the desired destination with cc and bcc option. The
163      * subject can also be mentionned. Also the
164      *
165      * @param from The message sender
166      * @param to The message destination.
167      * @param cc The message copy destination.
168      * @param bcc The message copy blind destination.
169      * @param subject The message subject.
170      * @param mailhost A self defined mail host.
171      * @param message The message to send.
172      * @param htmlFormat true if message MIME type is text/html, false if message is plain text
173      * @return True if message is sent successfully, false otherwise
174      */

175     public boolean sendMessage(String JavaDoc from, String JavaDoc to, String JavaDoc cc, String JavaDoc bcc,
176                                String JavaDoc subject, String JavaDoc mailhost, String JavaDoc message, boolean htmlFormat) {
177         try {
178             if (to == null) {
179                 to = defaultRecipient();
180             }
181             if (from == null) {
182                 from = defaultSender();
183             }
184
185             if (mailhost == null || to == null || from == null) {
186                 logger.debug("Mail settings not valid, ignoring...");
187                 return false;
188             }
189             if (mailhost.equals("") || to.equals("") || from.equals("")) {
190                 logger.debug("Mail settings not valid, ignoring...");
191                 return false;
192             }
193             logger.debug("Send mail using settings mailhost=[" + mailhost +
194                          "] to=[" + to + "] from=[" + from + "]");
195             Properties JavaDoc props = System.getProperties();
196             props.put("mail.smtp.host", mailhost);
197             // Get a Session object
198
Session JavaDoc session = Session.getDefaultInstance(props, null);
199             // construct the message
200
Message JavaDoc msg = new MimeMessage JavaDoc(session);
201             if (from != null) {
202                 msg.setFrom(new InternetAddress JavaDoc(from));
203             } else {
204                 msg.setFrom();
205             }
206             msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
207             if (cc != null) {
208                 msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
209             }
210             if (bcc != null) {
211                 msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
212             }
213             if (subject == null || "".equals(subject)) {
214                 subject = "[JAHIA] Jahia Message";
215             }
216             msg.setSubject(subject);
217
218             StringWriter JavaDoc msgBodyWriter = new StringWriter JavaDoc();
219             PrintWriter JavaDoc strOut = new PrintWriter JavaDoc(msgBodyWriter);
220             strOut.println(message);
221
222             if (!htmlFormat)
223               msg.setText(msgBodyWriter.toString());
224             else
225               msg.setContent(msgBodyWriter.toString(), "text/html");
226             
227             msg.setHeader("X-Mailer", mailer);
228             msg.setSentDate(new Date JavaDoc());
229             logger.debug("Mailing to " + to + " via " + mailhost + "...");
230
231             // send the thing off
232
sendMessage(msg);
233             logger.debug("Mail was sent successfully.");
234         } catch (Throwable JavaDoc th) {
235             logger.debug("Error while sending mail : " + th.getMessage(), th);
236             return false;
237         }
238         return true;
239     }
240
241     /**
242      * Send a Message type previously initialized and formated.
243      *
244      * @param msg The Message to send.
245      * @return True if message is sent successfully, false otherwise
246      */

247     public boolean sendMessage(Message JavaDoc message) {
248         try {
249             Transport.send(message);
250         } catch (Throwable JavaDoc th) {
251             logger.debug("Error while sending mail : " + th.getMessage(), th);
252             return false;
253         }
254         return true;
255     }
256
257     /**
258      *
259      * Send a message to the desired addressee with the specified subject, message
260      * and attachments, using the default mail host.
261      *
262      * @param from The message sender
263      * @param to The message destination.
264      * @param subject The message subject.
265      * @param message The message to send.
266      * @param attachments The attachments to add to the message.
267      * @return True if message is sent successfully, false otherwise
268      */

269     public boolean sendMessage(
270       String JavaDoc from,
271       String JavaDoc to,
272       String JavaDoc subject,
273       Multipart JavaDoc multipart) {
274       try {
275         if (to == null) {
276           to = defaultRecipient();
277         }
278         if (from == null) {
279           from = defaultSender();
280         }
281
282         if (mailhost == null || to == null || from == null) {
283           logger.debug("*** sendMessage : Mail settings not valid, ignoring...");
284           return false;
285         }
286         if (mailhost.equals("") || to.equals("") || from.equals("")) {
287           logger.debug("*** sendMessage : Mail settings not valid, ignoring...");
288           return false;
289         }
290         logger.debug(
291           "Send mail using settings mailhost=["
292             + mailhost
293             + "] to=["
294             + to
295             + "] from=["
296             + from
297             + "]");
298         Properties JavaDoc props = System.getProperties();
299         props.put("mail.smtp.host", mailhost);
300         // Get a Session object
301
Session JavaDoc session = Session.getDefaultInstance(props, null);
302         // Construct the message
303
MimeMessage JavaDoc msg = new MimeMessage JavaDoc(session);
304
305
306         if (from != null) {
307           msg.setFrom(new InternetAddress JavaDoc(from));
308         } else {
309           msg.setFrom();
310         }
311         msg.setRecipients(
312           Message.RecipientType.TO,
313           InternetAddress.parse(to, false));
314
315         if (subject == null || "".equals(subject)) {
316           subject = "[JAHIA] Jahia Message";
317         }
318
319         msg.setSubject(subject, "ISO-8859-1");
320         msg.setHeader("X-Mailer", mailer);
321         msg.setSentDate(new Date JavaDoc());
322
323         if (multipart != null) {
324           msg.setContent(multipart);
325         }
326
327         Transport.send(msg);
328
329         // --------------------------------------
330
logger.debug("*** sendMessage : Mailing to " + to + " via " + mailhost + "...");
331
332         // send the thing off
333
// sendMessage(msg);
334
logger.debug("*** sendMessage : Mail was sent successfully.");
335
336       } catch (Throwable JavaDoc th) {
337         logger.error("*** sendMessage : Error while sending mail : " + th.getMessage(), th);
338         return false;
339       }
340       return true;
341     }
342
343     public String JavaDoc defaultRecipient() {
344         return this.to;
345     }
346
347     public String JavaDoc defaultSender() {
348         return this.from;
349     }
350
351     // Mail settings
352
private String JavaDoc to;
353     private String JavaDoc subject;
354     private String JavaDoc from;
355     private String JavaDoc mailhost;
356     private String JavaDoc mailer = "Jahia Server v." + JahiaInterface.RELEASE_NUMBER +
357                             "." + JahiaInterface.SERVICE_PACK_NUMBER +
358                             " build " + JahiaInterface.BUILD_NUMBER;
359
360     static private MailService singletonInstance = null;
361
362     private static org.apache.log4j.Logger logger =
363             org.apache.log4j.Logger.getLogger(MailService.class);
364
365 }
Popular Tags