KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > quercus > lib > MailModule


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  *
23  * Free Software Foundation, Inc.
24  * 59 Temple Place, Suite 330
25  * Boston, MA 02111-1307 USA
26  *
27  * @author Scott Ferguson
28  */

29
30 package com.caucho.quercus.lib;
31
32 import com.caucho.quercus.QuercusModuleException;
33 import com.caucho.quercus.annotation.Optional;
34 import com.caucho.quercus.env.Env;
35 import com.caucho.quercus.env.StringValue;
36 import com.caucho.quercus.module.AbstractQuercusModule;
37 import com.caucho.util.L10N;
38
39 import javax.mail.Address JavaDoc;
40 import javax.mail.Message JavaDoc;
41 import javax.mail.MessagingException JavaDoc;
42 import javax.mail.Session JavaDoc;
43 import javax.mail.Transport JavaDoc;
44 import javax.mail.internet.InternetAddress JavaDoc;
45 import javax.mail.internet.MimeMessage JavaDoc;
46 import java.util.ArrayList JavaDoc;
47 import java.util.Properties JavaDoc;
48 import java.util.logging.Level JavaDoc;
49 import java.util.logging.Logger JavaDoc;
50
51 /**
52  * PHP functions implemented from the mail module
53  */

54 public class MailModule extends AbstractQuercusModule {
55   private static final Logger JavaDoc log =
56     Logger.getLogger(MailModule.class.getName());
57
58   private static final L10N L = new L10N(MailModule.class);
59
60   /**
61    * Send mail using JavaMail.
62    */

63   public static boolean mail(Env env,
64                              String JavaDoc to,
65                              String JavaDoc subject,
66                              StringValue message,
67                              @Optional String JavaDoc additionalHeaders,
68                              @Optional String JavaDoc additionalParameters)
69   {
70     Transport JavaDoc smtp = null;
71
72     try {
73       Properties JavaDoc props = new Properties JavaDoc();
74
75       StringValue host = env.getIni("SMTP");
76       if (host != null && ! host.toString().equals(""))
77         props.put("mail.smtp.host", host.toString());
78
79       StringValue port = env.getIni("smtp_port");
80       if (port != null && ! port.toString().equals(""))
81         props.put("mail.smtp.port", port.toString());
82
83       StringValue user = env.getIni("sendmail_from");
84       if (user != null && ! user.toString().equals(""))
85         props.put("mail.from", user.toString());
86
87       Session JavaDoc mailSession = Session.getInstance(props, null);
88       smtp = mailSession.getTransport("smtp");
89
90       MimeMessage JavaDoc msg = new MimeMessage JavaDoc(mailSession);
91       msg.setFrom();
92       msg.setSubject(subject);
93       msg.setContent(message.toString(), "text/plain");
94
95       ArrayList JavaDoc<Address JavaDoc> addrList;
96       addrList = addRecipients(msg, Message.RecipientType.TO, to);
97
98       if (additionalHeaders != null)
99         addHeaders(msg, additionalHeaders);
100
101       msg.saveChanges();
102
103       if (addrList.size() == 0)
104         throw new QuercusModuleException(L.l("mail has no recipients"));
105
106       String JavaDoc username = env.getIniString("smtp_username");
107       String JavaDoc password = env.getIniString("smtp_password");
108
109       if (password != null && ! "".equals(password))
110         smtp.connect(username, password);
111       else
112         smtp.connect();
113
114       Address JavaDoc[] addr = new Address JavaDoc[addrList.size()];
115       addrList.toArray(addr);
116
117       smtp.sendMessage(msg, addr);
118
119       log.fine("quercus-mail: sent mail to " + to);
120
121       return true;
122     } catch (RuntimeException JavaDoc e) {
123       log.log(Level.FINER, e.toString(), e);
124
125       throw e;
126     } catch (MessagingException JavaDoc e) {
127       log.log(Level.FINE, e.toString(), e);
128
129       env.warning(e.getMessage());
130
131       return false;
132     } catch (Exception JavaDoc e) {
133       log.log(Level.FINE, e.toString(), e);
134
135       env.warning(e.toString());
136
137       return false;
138     } finally {
139       try {
140         if (smtp != null)
141           smtp.close();
142       } catch (Exception JavaDoc e) {
143         log.log(Level.FINER, e.toString(), e);
144       }
145     }
146   }
147
148   private static ArrayList JavaDoc<Address JavaDoc> addRecipients(MimeMessage JavaDoc msg,
149                                                   Message.RecipientType JavaDoc type,
150                                                   String JavaDoc to)
151     throws MessagingException JavaDoc
152   {
153     String JavaDoc []split = to.split("[ \t,<>]");
154
155     ArrayList JavaDoc<Address JavaDoc> addresses = new ArrayList JavaDoc<Address JavaDoc>();
156
157     for (int i = 0; i < split.length; i++) {
158       if (split[i].indexOf('@') > 0) {
159         Address JavaDoc addr = new InternetAddress JavaDoc(split[i]);
160
161         addresses.add(addr);
162         msg.addRecipient(type, addr);
163       }
164     }
165
166     return addresses;
167   }
168
169   private static void addHeaders(MimeMessage JavaDoc msg, String JavaDoc headers)
170     throws MessagingException JavaDoc
171   {
172     int i = 0;
173     int len = headers.length();
174
175     while (true) {
176       char ch;
177
178       for (;
179            i < len && Character.isWhitespace(headers.charAt(i));
180            i++) {
181       }
182
183       if (len <= i)
184         return;
185
186       StringBuilder JavaDoc name = new StringBuilder JavaDoc();
187
188       for (;
189            i < len && (! Character.isWhitespace(ch = headers.charAt(i)) &&
190                        ch != ':');
191            i++) {
192         name.append((char) ch);
193       }
194
195       for (;
196            i < len && (Character.isWhitespace(ch = headers.charAt(i)) ||
197                        ch == ':');
198            i++) {
199       }
200
201       StringBuilder JavaDoc value = new StringBuilder JavaDoc();
202
203       for (;
204            i < len && ((ch = headers.charAt(i)) != '\r' &&
205                        ch != '\n');
206            i++) {
207         value.append((char) ch);
208       }
209
210       msg.addHeader(name.toString(), value.toString());
211     }
212   }
213 }
214
215
Popular Tags