KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > util > mail > Spammer


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

43 package net.jforum.util.mail;
44
45 import java.io.StringWriter JavaDoc;
46 import java.util.Date JavaDoc;
47 import java.util.Iterator JavaDoc;
48 import java.util.List JavaDoc;
49 import java.util.Properties JavaDoc;
50
51 import javax.mail.Address JavaDoc;
52 import javax.mail.Message JavaDoc;
53 import javax.mail.MessagingException JavaDoc;
54 import javax.mail.Session JavaDoc;
55 import javax.mail.Transport JavaDoc;
56 import javax.mail.internet.InternetAddress JavaDoc;
57 import javax.mail.internet.MimeMessage JavaDoc;
58
59 import net.jforum.JForumExecutionContext;
60 import net.jforum.util.preferences.ConfigKeys;
61 import net.jforum.util.preferences.SystemGlobals;
62
63 import org.apache.log4j.Logger;
64
65 import freemarker.template.SimpleHash;
66 import freemarker.template.Template;
67
68 /**
69  * Dispatch emails to the world. TODO: should do some refactoring to send a personalized email to
70  * each user.
71  *
72  * @author Rafael Steil
73  * @version $Id: Spammer.java,v 1.21 2006/02/28 01:10:47 rafaelsteil Exp $
74  */

75 public class Spammer
76 {
77     private static final Logger logger = Logger.getLogger(Spammer.class);
78
79     private static int MESSAGE_HTML = 0;
80     private static int MESSAGE_TEXT = 1;
81
82     private Properties JavaDoc mailProps = new Properties JavaDoc();
83     private static int messageFormat;
84     private static Session JavaDoc session;
85     private static String JavaDoc username;
86     private static String JavaDoc password;
87     private MimeMessage JavaDoc message;
88     private String JavaDoc messageText;
89
90     protected Spammer() throws EmailException
91     {
92         String JavaDoc host = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST);
93         
94         if (host != null) {
95             int colon = host.indexOf(':');
96
97             if (colon > 0) {
98                 mailProps.put("mail.smtp.host", host.substring(0, colon));
99                 mailProps.put("mail.smtp.port", String.valueOf(host.substring(colon + 1)));
100             }
101             else {
102                 mailProps.put("mail.smtp.host", SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST));
103             }
104             
105             String JavaDoc port = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PORT);
106             
107             if (port != null) {
108                 mailProps.put("mail.smtp.port", port);
109             }
110             
111             String JavaDoc localhost = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_LOCALHOST);
112             
113             if (localhost != null && localhost.trim().length() > 0) {
114                 mailProps.put("mail.smtp.localhost", localhost);
115             }
116         }
117         
118         mailProps.put("mail.mime.address.strict", "false");
119         mailProps.put("mail.mime.charset", SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET));
120         mailProps.put("mail.smtp.auth", SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_AUTH));
121
122         username = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_USERNAME);
123         password = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PASSWORD);
124
125         messageFormat = SystemGlobals.getValue(ConfigKeys.MAIL_MESSSAGE_FORMAT).equals("html")
126             ? MESSAGE_HTML
127             : MESSAGE_TEXT;
128
129         session = Session.getDefaultInstance(mailProps);
130     }
131
132     public static Session JavaDoc getSession()
133     {
134         return session;
135     }
136
137     public final Message JavaDoc getMesssage()
138     {
139         return this.message;
140     }
141
142     public boolean dispatchMessages() throws Exception JavaDoc
143     {
144         if (SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_AUTH)) {
145             if (username != null && !username.equals("") && password != null && !password.equals("")) {
146                 Transport JavaDoc transport = Spammer.getSession().getTransport("smtp");
147
148                 try {
149                     String JavaDoc host = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST);
150                     if (host != null) {
151                         int colon = host.indexOf(':');
152                         if (colon > 0) {
153                             transport.connect(host.substring(0, colon), Integer.parseInt(host.substring(colon + 1)),
154                                     username, password);
155                         }
156                         else {
157                             transport.connect(host, username, password);
158                         }
159                     }
160                 }
161                 catch (MessagingException JavaDoc e) {
162                     throw new EmailException("Could not connect to the mail server", e);
163                 }
164
165                 if (transport.isConnected()) {
166                     Address JavaDoc[] addresses = message.getAllRecipients();
167                     for (int i = 0; i < addresses.length; i++) {
168                         // Tricks and tricks
169
message.setRecipient(Message.RecipientType.TO, addresses[i]);
170                         transport.sendMessage(message, new Address JavaDoc[] { addresses[i] });
171                     }
172                 }
173                 
174                 transport.close();
175             }
176         }
177         else {
178             Address JavaDoc[] addresses = message.getAllRecipients();
179             for (int i = 0; i < addresses.length; i++) {
180                 message.setRecipient(Message.RecipientType.TO, addresses[i]);
181                 Transport.send(message, new Address JavaDoc[] { addresses[i] });
182             }
183         }
184
185         return true;
186     }
187
188     protected final void prepareMessage(List JavaDoc addresses, SimpleHash params, String JavaDoc subject, String JavaDoc messageFile)
189             throws EmailException
190     {
191         this.message = new MimeMessage JavaDoc(session);
192         
193         params.put("forumName", SystemGlobals.getValue(ConfigKeys.FORUM_NAME));
194
195         try {
196             InternetAddress JavaDoc[] recipients = new InternetAddress JavaDoc[addresses.size()];
197
198             String JavaDoc charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET);
199
200             this.message.setSentDate(new Date JavaDoc());
201             this.message.setFrom(new InternetAddress JavaDoc(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER)));
202             this.message.setSubject(subject, charset);
203
204             this.messageText = this.getMessageText(params, messageFile);
205
206             if (messageFormat == MESSAGE_HTML) {
207                 this.message.setContent(this.messageText, "text/html; charset=" + charset);
208             }
209             else {
210                 this.message.setText(this.messageText, charset);
211             }
212
213             int i = 0;
214             for (Iterator JavaDoc iter = addresses.iterator(); iter.hasNext(); i++) {
215                 recipients[i] = new InternetAddress JavaDoc((String JavaDoc) iter.next());
216             }
217
218             this.message.setRecipients(Message.RecipientType.TO, recipients);
219         }
220         catch (Exception JavaDoc e) {
221             logger.warn(e);
222             throw new EmailException(e);
223         }
224     }
225     
226     /**
227      * Gets the message text to send in the email.
228      *
229      * @param params The optional params. If no need of any, just pass null
230      * @param messageFile The optional message file to load the text.
231      * @return The email message text
232      * @throws Exception
233      */

234     protected String JavaDoc getMessageText(SimpleHash params, String JavaDoc messageFile) throws Exception JavaDoc
235     {
236         String JavaDoc templateEncoding = SystemGlobals.getValue(ConfigKeys.MAIL_TEMPLATE_ENCODING);
237         
238         StringWriter JavaDoc sWriter = new StringWriter JavaDoc();
239         
240         Template template = null;
241         
242         if (templateEncoding == null || "".equals(templateEncoding.trim())) {
243             template = JForumExecutionContext.templateConfig().getTemplate(messageFile);
244         }
245         else {
246             template = JForumExecutionContext.templateConfig().getTemplate(messageFile, templateEncoding);
247         }
248         
249         template.process(params, sWriter);
250         
251         return sWriter.toString();
252     }
253
254     /**
255      * Gets the email body
256      *
257      * @return String with the email body that will be sent to the user
258      */

259     public String JavaDoc getMessageBody()
260     {
261         return this.messageText;
262     }
263 }
264
Popular Tags