KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openbravo > erpCommon > businessUtility > EMail


1 /*
2  ******************************************************************************
3  * The contents of this file are subject to the Compiere License Version 1.1
4  * ("License"); You may not use this file except in compliance with the License
5  * You may obtain a copy of the License at http://www.compiere.org/license.html
6  * Software distributed under the License is distributed on an "AS IS" basis,
7  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
8  * the specific language governing rights and limitations under the License.
9  * The Original Code is Compiere ERP & CRM Business Solution
10  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
11  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
12  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
13  * Contributor(s): Openbravo SL
14  * Contributions are Copyright (C) 2001-2006 Openbravo S.L.
15  ******************************************************************************
16 */

17 package org.openbravo.erpCommon.businessUtility;
18
19 import org.openbravo.base.secureApp.VariablesSecureApp;
20 import java.util.*;
21 import java.io.*;
22 import java.net.*;
23 import javax.mail.*;
24 import javax.mail.internet.*;
25 import javax.activation.*;
26 import com.sun.mail.smtp.*;
27 import org.apache.log4j.Logger ;
28
29
30 public class EMail {
31   static Logger log4j = Logger.getLogger(EMail.class);
32   private String JavaDoc g_from;
33   private ArrayList<InternetAddress> g_to;
34   private ArrayList<InternetAddress> g_cc;
35   private ArrayList<InternetAddress> g_bcc;
36   private ArrayList<Object JavaDoc> g_attachments;
37   private InternetAddress g_replyTo;
38   private String JavaDoc g_subject;
39   private String JavaDoc g_message;
40   private String JavaDoc g_smtpHost;
41   private VariablesSecureApp g_vars;
42   private EMailAuthenticator g_auth;
43   private SMTPMessage g_smtpMsg;
44   private String JavaDoc g_messageHTML;
45   private boolean g_valid;
46
47   public EMail (VariablesSecureApp vars, String JavaDoc smtpHost, String JavaDoc from, String JavaDoc to) {
48     g_from=from;
49     addTo(to);
50     g_smtpHost=smtpHost;
51     g_vars=vars;
52   }
53
54   public EMail(VariablesSecureApp vars, String JavaDoc smtpHost, String JavaDoc from, String JavaDoc to, String JavaDoc subject, String JavaDoc message) {
55     g_from=from;
56     addTo(to);
57     g_subject=subject;
58     g_message=message;
59     g_smtpHost=smtpHost;
60     g_vars=vars;
61     g_valid = isValid(true);
62   }
63
64   private void dumpMessage() {
65     if (g_smtpMsg == null) return;
66     try {
67       Enumeration e = g_smtpMsg.getAllHeaderLines ();
68       while (e.hasMoreElements ()) if (log4j.isDebugEnabled()) log4j.debug("- " + e.nextElement ());
69     } catch (MessagingException ex) {
70       log4j.error("dumpMessage" + ex);
71     }
72   }
73
74   protected MimeMessage getMimeMessage() {
75         return g_smtpMsg;
76     }
77
78   public void setEMailUser(String JavaDoc username, String JavaDoc password) {
79     if(username == null || password == null) log4j.warn("setEMailUser ignored - " + username + "/" + password);
80     else {
81       g_auth = new EMailAuthenticator(username, password);
82       if (g_auth==null) g_valid = false;
83     }
84   }
85
86   private void setEMailUser() {
87     if(g_auth != null) return;
88     String JavaDoc from = g_from;
89     String JavaDoc email = g_vars.getSessionValue("#User_EMail");
90     String JavaDoc usr = g_vars.getSessionValue("#User_EMailUser");
91     String JavaDoc pwd = g_vars.getSessionValue("#User_EMailUserPw");
92     if(from.equals(email) && usr.length() > 0 && pwd.length() > 0) {
93       setEMailUser(usr, pwd);
94       return;
95     }
96     email = g_vars.getSessionValue("#Request_EMail");
97     usr = g_vars.getSessionValue("#Request_EMailUser");
98     pwd = g_vars.getSessionValue("#Request_EMailUserPw");
99     if(from.equals(email) && usr.length() > 0 && pwd.length() > 0) setEMailUser(usr, pwd);
100   }
101
102   public String JavaDoc send() {
103     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
104     Properties props = new Properties();
105     props.put("mail.debug", "true");
106     props.put("mail.store.protocol", "smtp");
107     props.put("mail.transport.protocol", "smtp");
108     props.put("mail.host", g_smtpHost);
109
110     setEMailUser();
111     if(g_auth != null) props.put("mail.smtp.auth", "true");
112
113     Session session = Session.getInstance(props, g_auth);
114     session.setDebug(true);
115
116     try {
117       g_smtpMsg = new SMTPMessage(session);
118       g_smtpMsg.setFrom(new InternetAddress(g_from));
119       
120       InternetAddress[] address = getTos();
121       if (address.length == 1) g_smtpMsg.setRecipient(Message.RecipientType.TO, address[0]);
122       else g_smtpMsg.setRecipients(Message.RecipientType.TO, address);
123       address = getCcs();
124       if (address != null && address.length > 0) g_smtpMsg.setRecipients (Message.RecipientType.CC, address);
125       address = getBccs();
126       if (address != null && address.length > 0) g_smtpMsg.setRecipients (Message.RecipientType.BCC, address);
127       if (g_replyTo != null) g_smtpMsg.setReplyTo(new Address[] {g_replyTo});
128       g_smtpMsg.setSentDate(new java.util.Date JavaDoc());
129       g_smtpMsg.setHeader("Comments", "CompiereMail");
130       g_smtpMsg.setAllow8bitMIME(true);
131       g_smtpMsg.setNotifyOptions(SMTPMessage.NOTIFY_FAILURE | SMTPMessage.NOTIFY_SUCCESS);
132       g_smtpMsg.setReturnOption(SMTPMessage.RETURN_HDRS);
133       setContent();
134       g_smtpMsg.saveChanges();
135       Transport t = session.getTransport("smtp");
136       t.connect();
137       Transport.send(g_smtpMsg);
138     } catch (MessagingException mex) {
139       log4j.error("Exception handling in EMail.java: " + mex.toString());
140       sb.append("Exception handling in EMail.java\n");
141
142       mex.printStackTrace();
143       Exception JavaDoc ex = mex;
144       do {
145         if (ex instanceof SendFailedException) {
146           SendFailedException sfex = (SendFailedException)ex;
147           Address[] invalid = sfex.getInvalidAddresses();
148           if (invalid != null) {
149             log4j.error(" ** Invalid Addresses");
150             sb.append(" ** Invalid Addresses\n");
151             if (invalid != null) {
152               for (int i = 0; i < invalid.length; i++) {
153                 log4j.error(" " + invalid[i]);
154                 sb.append(" " + invalid[i] + "\n");
155               }
156             }
157           }
158           Address[] validUnsent = sfex.getValidUnsentAddresses();
159           if (validUnsent != null) {
160             log4j.error(" ** ValidUnsent Addresses");
161             sb.append(" ** ValidUnsent Addresses\n");
162             if (validUnsent != null) {
163               for (int i = 0; i < validUnsent.length; i++) {
164                 log4j.error(" "+validUnsent[i]);
165                 sb.append(" "+validUnsent[i] + "\n");
166               }
167             }
168           }
169           Address[] validSent = sfex.getValidSentAddresses();
170           if (validSent != null) {
171             log4j.error(" ** ValidSent Addresses");
172             sb.append(" ** ValidSent Addresses\n");
173             if (validSent != null) {
174               for (int i = 0; i < validSent.length; i++) {
175                 log4j.error(" "+validSent[i]);
176                 sb.append(" "+validSent[i] + "\n");
177               }
178             }
179           }
180         }
181         if (ex instanceof MessagingException) ex = ((MessagingException)ex).getNextException();
182         else ex = null;
183       } while (ex != null);
184     } catch (Exception JavaDoc e) {
185       log4j.error("send" + e);
186       return "EMail.send: " + e.getLocalizedMessage();
187     }
188     return (sb.toString().equals("")?"OK":sb.toString());
189   }
190
191   public boolean isValid() {
192     return g_valid;
193   }
194
195   public boolean isValid(boolean recheck) {
196     if(g_from == null || g_from.equals("")) {
197       log4j.warn("EMail.isValid - From is invalid=" + g_from);
198       return false;
199     }
200     InternetAddress ia = getTo();
201     if (ia == null || ia.getAddress().length() == 0) {
202       log4j.warn("EMail.isValid - To is invalid=" + g_to);
203       return false;
204     }
205     if(g_smtpHost == null || g_smtpHost.equals("")) {
206       log4j.warn("EMail.isValid - SMTP Host is invalid" + g_smtpHost);
207       return false;
208     }
209     if(g_subject == null || g_subject.equals("")) {
210       log4j.warn("EMail.isValid - Subject is invalid=" + g_subject);
211       return false;
212     } else {
213       return true;
214     }
215   }
216
217   private void setContent () throws MessagingException, IOException {
218     g_smtpMsg.setSubject(getSubject());
219
220     // Simple Message
221
if (g_attachments == null || g_attachments.size() == 0) {
222       if (g_messageHTML == null || g_messageHTML.length () == 0) g_smtpMsg.setContent(getMessageCRLF(), "text/plain");
223       else g_smtpMsg.setDataHandler(new DataHandler(new ByteArrayDataSource (g_messageHTML, "text/html")));
224       
225       if (log4j.isDebugEnabled()) log4j.debug("setContent(simple) " + getSubject());
226     } else { // Multi part message
227
// First Part - Message
228
MimeBodyPart mbp_1 = new MimeBodyPart();
229       mbp_1.setText("");
230       if (g_messageHTML == null || g_messageHTML.length () == 0) mbp_1.setContent (getMessageCRLF(), "text/plain");
231       else mbp_1.setDataHandler (new DataHandler(new ByteArrayDataSource (g_messageHTML, "text/html")));
232
233       // Create Multipart and its parts to it
234
Multipart mp = new MimeMultipart();
235       mp.addBodyPart(mbp_1);
236       if (log4j.isDebugEnabled()) log4j.debug("setContent (multi) " + getSubject() + " - " + mbp_1);
237
238       // for all attachments
239
for (int i = 0; i < g_attachments.size(); i++) {
240         Object JavaDoc attachment = g_attachments.get(i);
241         DataSource ds = null;
242         if (attachment instanceof File) {
243           File file = (File)attachment;
244           if (file.exists()) ds = new FileDataSource (file);
245           else {
246             log4j.error("setContent - File does not exist: " + file);
247             continue;
248           }
249         } else if (attachment instanceof URL) {
250           URL url = (URL)attachment;
251           ds = new URLDataSource (url);
252         } else if (attachment instanceof DataSource) ds = (DataSource)attachment;
253         else {
254           log4j.error("setContent - Attachement type unknown: " + attachment);
255           continue;
256         }
257         // Attachment Part
258
MimeBodyPart mbp_2 = new MimeBodyPart();
259         mbp_2.setDataHandler(new DataHandler(ds));
260         mbp_2.setFileName(ds.getName());
261         if (log4j.isDebugEnabled()) log4j.debug("setContent - Added Attachment " + ds.getName() + " - " + mbp_2);
262         mp.addBodyPart(mbp_2);
263       }
264
265       // Add to Message
266
g_smtpMsg.setContent(mp);
267     } // multi=part
268
} // setContent*/
269

270   public void setMessageHTML (String JavaDoc html) {
271     if (html == null || html.length() == 0) g_valid = false;
272     else {
273       g_messageHTML = html;
274       if (!g_messageHTML.endsWith("\n")) g_messageHTML += "\n";
275     }
276   }
277
278   public void setMessageHTML (String JavaDoc subject, String JavaDoc message) {
279     g_subject = subject;
280     StringBuffer JavaDoc sb = new StringBuffer JavaDoc("<HTML>\n").append("<HEAD>\n").append("<TITLE>\n").append(subject + "\n").append("</TITLE>\n");
281     sb.append("</HEAD>\n");
282     sb.append("<BODY>\n");
283     sb.append("<H2>").append(subject).append("</H2>\n");
284     sb.append(message);
285     sb.append("\n");
286     sb.append("</BODY>\n");
287     sb.append("</HTML>\n");
288     g_messageHTML = sb.toString();
289   }
290
291   public String JavaDoc getMessageHTML() {
292     return g_messageHTML;
293   }
294
295   public void setFrom(String JavaDoc newFrom) {
296     if (newFrom == null || newFrom.equals("")) {
297       g_valid = false;
298       return;
299     }
300     g_from = newFrom;
301   }
302
303   public String JavaDoc getFrom() {
304     return g_from;
305   }
306
307   public boolean addTo (String JavaDoc newTo) {
308     if (newTo == null || newTo.length() == 0) {
309       g_valid = false;
310       return false;
311     }
312     try {
313       InternetAddress ia = new InternetAddress (newTo);
314       if (g_to == null) g_to = new ArrayList<InternetAddress>();
315       g_to.add(ia);
316     } catch (Exception JavaDoc e) {
317       log4j.error("addTo - " + e.toString());
318       g_valid = false;
319       return false;
320     }
321     return true;
322   }
323
324   public InternetAddress getTo() {
325     if (g_to == null || g_to.size() == 0) return null;
326     InternetAddress ia = g_to.get(0);
327     return ia;
328   }
329
330   public InternetAddress[] getTos() {
331     if (g_to == null || g_to.size() == 0) return null;
332     InternetAddress[] ias = new InternetAddress[g_to.size()];
333     g_to.toArray(ias);
334     return ias;
335   }
336
337   public boolean addCc (String JavaDoc newCc) {
338     if (newCc == null || newCc.length() == 0) return false;
339     InternetAddress ia = null;
340     try {
341       ia = new InternetAddress (newCc);
342     } catch (Exception JavaDoc e) {
343       log4j.error("addCc" + e);
344       return false;
345     }
346     if (g_cc == null) g_cc = new ArrayList<InternetAddress>();
347     g_cc.add (ia);
348     return true;
349   }
350
351   public InternetAddress[] getCcs() {
352     if (g_cc == null || g_cc.size() == 0) return null;
353     InternetAddress[] ias = new InternetAddress[g_cc.size()];
354     g_cc.toArray(ias);
355     return ias;
356   }
357
358   public boolean addBcc (String JavaDoc newBcc) {
359     if (newBcc == null || newBcc.length() == 0) return false;
360     InternetAddress ia = null;
361     try {
362       ia = new InternetAddress (newBcc);
363     } catch (Exception JavaDoc e) {
364       log4j.error("addBcc" + e);
365       return false;
366     }
367     if (g_bcc == null) g_bcc = new ArrayList<InternetAddress>();
368     g_bcc.add (ia);
369     return true;
370   }
371
372   public InternetAddress[] getBccs() {
373     if (g_bcc == null || g_bcc.size() == 0) return null;
374     InternetAddress[] ias = new InternetAddress[g_bcc.size()];
375     g_bcc.toArray(ias);
376     return ias;
377   }
378
379   public boolean setReplyTo (String JavaDoc newTo) {
380     if (newTo == null || newTo.length() == 0) return false;
381     InternetAddress ia = null;
382     try {
383       ia = new InternetAddress (newTo);
384     } catch (Exception JavaDoc e) {
385       log4j.error("setReplyTo" + e);
386       return false;
387     }
388     g_replyTo = ia;
389     return true;
390   }
391
392   public InternetAddress getReplyTo() {
393     return g_replyTo;
394   }
395
396   public void setSubject(String JavaDoc newSubject) {
397     if (newSubject == null || newSubject.length() == 0) g_valid = false;
398     else g_subject = newSubject;
399   }
400
401   public String JavaDoc getSubject() {
402     return g_subject;
403   }
404
405   public void setMessage(String JavaDoc newMessage) {
406     if (newMessage == null || newMessage.length() == 0) g_valid = false;
407     else {
408       g_message = newMessage;
409       if (!g_message.endsWith("\n"))
410         g_message += "\n";
411     }
412   }
413
414   public String JavaDoc getMessage() {
415     return g_message;
416   }
417
418   public String JavaDoc getMessageCRLF() {
419     if (g_message == null) return "";
420     char[] chars = g_message.toCharArray();
421     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
422     for (int i = 0; i < chars.length; i++) {
423       char c = chars[i];
424       if (c == '\n') {
425         int previous = i-1;
426         if (previous >= 0 && chars[previous] == '\r') sb.append(c);
427         else sb.append("\r\n");
428       } else sb.append(c);
429     }
430     return sb.toString();
431   }
432
433   public void setSmtpHost(String JavaDoc newSmtpHost) {
434     if (newSmtpHost == null || newSmtpHost.length() == 0) g_valid = false;
435     else g_smtpHost = newSmtpHost;
436   }
437
438   public String JavaDoc getSmtpHost() {
439     return g_smtpHost;
440   }
441
442   public void setSmtpMessage(SMTPMessage newSmtpMsg) {
443     g_smtpMsg = newSmtpMsg;
444   }
445
446   public SMTPMessage getSmtpMessage() {
447     return g_smtpMsg;
448   }
449
450   public void addAttachment (File file) {
451     if (file == null) return;
452     if (g_attachments == null) g_attachments = new ArrayList<Object JavaDoc>();
453     g_attachments.add(file);
454   }
455
456   public void addAttachment (URL url) {
457     if (url == null) return;
458     if (g_attachments == null) g_attachments = new ArrayList<Object JavaDoc>();
459     g_attachments.add(url);
460   }
461
462   public void addAttachment (byte[] data, String JavaDoc type, String JavaDoc name) {
463     ByteArrayDataSource byteArray = new ByteArrayDataSource (data, type).setName(name);
464     addAttachment (byteArray);
465   }
466
467   public void addAttachment (DataSource dataSource) {
468     if (dataSource == null) return;
469     if (g_attachments == null) g_attachments = new ArrayList<Object JavaDoc>();
470     g_attachments.add(dataSource);
471   }
472 }
473
Popular Tags