Spammer.java
Upload User: gdxydsw
Upload Date: 2019-01-29
Package Size: 16721k
Code Size: 12k
Category:

Java Develop

Development Platform:

Java

  1. /*
  2.  * Copyright (c) JForum Team
  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. import java.io.StringWriter;
  45. import java.util.ArrayList;
  46. import java.util.Date;
  47. import java.util.Iterator;
  48. import java.util.List;
  49. import java.util.Properties;
  50. import javax.mail.Address;
  51. import javax.mail.Message;
  52. import javax.mail.MessagingException;
  53. import javax.mail.Session;
  54. import javax.mail.Transport;
  55. import javax.mail.internet.InternetAddress;
  56. import javax.mail.internet.MimeMessage;
  57. import net.jforum.JForumExecutionContext;
  58. import net.jforum.entities.User;
  59. import net.jforum.exceptions.MailException;
  60. import net.jforum.util.preferences.ConfigKeys;
  61. import net.jforum.util.preferences.SystemGlobals;
  62. import org.apache.commons.lang.StringUtils;
  63. import org.apache.log4j.Logger;
  64. import freemarker.template.SimpleHash;
  65. import freemarker.template.Template;
  66. /**
  67.  * Dispatch emails to the world. 
  68.  * 
  69.  * @author Rafael Steil
  70.  * @version $Id: Spammer.java,v 1.36 2007/09/20 16:07:08 rafaelsteil Exp $
  71.  */
  72. public class Spammer
  73. {
  74. private static final Logger logger = Logger.getLogger(Spammer.class);
  75. private static final int MESSAGE_HTML = 0;
  76. private static final int MESSAGE_TEXT = 1;
  77. private static int messageFormat;
  78. private Session session;
  79. private String username;
  80. private String password;
  81. private Properties mailProps = new Properties();
  82. private MimeMessage message;
  83. private List users = new ArrayList();
  84. private String messageId;
  85. private String inReplyTo;
  86. private boolean needCustomization;
  87. private SimpleHash templateParams;
  88. private Template template;
  89. protected Spammer() throws MailException
  90. {
  91. boolean ssl = SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_SSL);
  92. String hostProperty = this.hostProperty(ssl);
  93. String portProperty = this.portProperty(ssl);
  94. String authProperty = this.authProperty(ssl);
  95. String localhostProperty = this.localhostProperty(ssl);
  96. mailProps.put(hostProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST));
  97. mailProps.put(portProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PORT));
  98. String localhost = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_LOCALHOST);
  99. if (!StringUtils.isEmpty(localhost)) {
  100. mailProps.put(localhostProperty, localhost);
  101. }
  102. mailProps.put("mail.mime.address.strict", "false");
  103. mailProps.put("mail.mime.charset", SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET));
  104. mailProps.put(authProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_AUTH));
  105. username = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_USERNAME);
  106. password = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PASSWORD);
  107. messageFormat = SystemGlobals.getValue(ConfigKeys.MAIL_MESSSAGE_FORMAT).equals("html") 
  108. ? MESSAGE_HTML
  109. : MESSAGE_TEXT;
  110. this.session = Session.getInstance(mailProps);
  111. }
  112. public boolean dispatchMessages()
  113. {
  114.         try
  115.         {
  116.             int sendDelay = SystemGlobals.getIntValue(ConfigKeys.MAIL_SMTP_DELAY);
  117.             
  118. if (SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_AUTH)) {
  119.                 if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
  120.                  boolean ssl = SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_SSL);
  121.                 
  122.                     Transport transport = this.session.getTransport(ssl ? "smtps" : "smtp");
  123.                     
  124.                     try {
  125.                     String host = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST);
  126.                     transport.connect(host, username, password);
  127.                     if (transport.isConnected()) {
  128.                         for (Iterator userIter = this.users.iterator(); userIter.hasNext(); ) {
  129.                          User user = (User)userIter.next();
  130.                         
  131.                          if (this.needCustomization) {
  132.                          this.defineUserMessage(user);
  133.                          }
  134.                         
  135.                          Address address = new InternetAddress(user.getEmail());
  136.                         
  137.                          logger.debug("Sending mail to: " + user.getEmail());
  138.                         
  139.                          this.message.setRecipient(Message.RecipientType.TO, address);                             
  140.                          transport.sendMessage(this.message, new Address[] { address });
  141.                         
  142.                          if (sendDelay > 0) {
  143.                          try {
  144.                              Thread.sleep(sendDelay);
  145.                             } 
  146.                          catch (InterruptedException ie) {
  147.                              logger.error("Error while Thread.sleep." + ie, ie);
  148.                             }
  149.                          }
  150.                         }
  151.                     }
  152.                     }
  153.                     catch (Exception e) {
  154.                      throw new MailException(e);
  155.                     }
  156.                     finally {
  157.                      try { transport.close(); } catch (Exception e) {}
  158.                     }
  159.                 }
  160.             }
  161.             else {
  162.                 for (Iterator iter = this.users.iterator(); iter.hasNext();) {
  163.                  User user = (User)iter.next();
  164.                 
  165.                  if (this.needCustomization) {
  166.                  this.defineUserMessage(user);
  167.                  }
  168.                 
  169.                  Address address = new InternetAddress(user.getEmail());
  170.                  logger.debug("Sending mail to: " + user.getEmail());
  171.                  this.message.setRecipient(Message.RecipientType.TO,address);
  172.                     Transport.send(this.message, new Address[] { address });
  173.                     
  174.                     if (sendDelay > 0) {
  175.                     try {
  176.                      Thread.sleep(sendDelay);
  177.                     } catch (InterruptedException ie) {
  178.                      logger.error("Error while Thread.sleep." + ie, ie);
  179.                     }
  180.                     }
  181.                 }
  182.             }
  183.         }
  184.         catch (MessagingException e) {
  185.             logger.error("Error while dispatching the message." + e, e);
  186.         }
  187.         return true;
  188. }
  189. private void defineUserMessage(User user)
  190. {
  191. try {
  192. this.templateParams.put("user", user);
  193. String text = this.processTemplate();
  194. this.defineMessageText(text);
  195. }
  196. catch (Exception e) {
  197. throw new MailException(e);
  198. }
  199. }
  200. /**
  201.  * Prepares the mail message for sending.
  202.  * 
  203.  * @param subject the subject of the email
  204.  * @param messageFile the path to the mail message template
  205.  * @throws MailException
  206.  */
  207. protected void prepareMessage(String subject, String messageFile) throws MailException
  208. {
  209. if (this.messageId != null) {
  210. this.message = new IdentifiableMimeMessage(session);
  211. ((IdentifiableMimeMessage)this.message).setMessageId(this.messageId);
  212. }
  213. else {
  214. this.message = new MimeMessage(session);
  215. }
  216. this.templateParams.put("forumName", SystemGlobals.getValue(ConfigKeys.FORUM_NAME));
  217. try {
  218. this.message.setSentDate(new Date());
  219. this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER)));
  220. this.message.setSubject(subject, SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET));
  221. if (this.inReplyTo != null) {
  222. this.message.addHeader("In-Reply-To", this.inReplyTo);
  223. }
  224. this.createTemplate(messageFile);
  225. this.needCustomization = this.isCustomizationNeeded();
  226. // If we don't need to customize any part of the message, 
  227. // then build the generic text right now
  228. if (!this.needCustomization) {
  229. String text = this.processTemplate();
  230. this.defineMessageText(text);
  231. }
  232. }
  233. catch (Exception e) {
  234. throw new MailException(e);
  235. }
  236. }
  237. /**
  238.  * Set the text contents of the email we're sending
  239.  * @param text the text to set
  240.  * @throws MessagingException
  241.  */
  242. private void defineMessageText(String text) throws MessagingException
  243. {
  244. String charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET);
  245. if (messageFormat == MESSAGE_HTML) {
  246. this.message.setContent(text.replaceAll("n", "<br />"), "text/html; charset=" + charset);
  247. }
  248. else {
  249. this.message.setText(text);
  250. }
  251. }
  252. /**
  253.  * Gets the message text to send in the email.
  254.  * 
  255.  * @param messageFile The optional message file to load the text. 
  256.  * @return The email message text
  257.  * @throws Exception
  258.  */
  259. protected void createTemplate(String messageFile) throws Exception
  260. {
  261. String templateEncoding = SystemGlobals.getValue(ConfigKeys.MAIL_TEMPLATE_ENCODING);
  262. if (StringUtils.isEmpty(templateEncoding)) {
  263. this.template = JForumExecutionContext.templateConfig().getTemplate(messageFile);
  264. }
  265. else {
  266. this.template = JForumExecutionContext.templateConfig().getTemplate(messageFile, templateEncoding);
  267. }
  268. }
  269. /**
  270.  * Merge the template data, creating the final content.
  271.  * This method should only be called after {@link #createTemplate(String)}
  272.  * and {@link #setTemplateParams(SimpleHash)}
  273.  * 
  274.  * @return the generated content
  275.  * @throws Exception
  276.  */
  277. protected String processTemplate() throws Exception
  278. {
  279. StringWriter writer = new StringWriter();
  280. this.template.process(this.templateParams, writer);
  281. return writer.toString();
  282. }
  283. /**
  284.  * Set the parameters for the template being processed
  285.  * @param params the parameters to the template
  286.  */
  287. protected void setTemplateParams(SimpleHash params)
  288. {
  289. this.templateParams = params;
  290. }
  291. /**
  292.  * Check if we have to send customized emails
  293.  * @return true if there is a need for customized emails
  294.  */
  295. private boolean isCustomizationNeeded()
  296. {
  297. boolean need = false;
  298. for (Iterator iter = this.users.iterator(); iter.hasNext(); ) {
  299. User user = (User)iter.next();
  300. if (user.notifyText()) {
  301. need = true;
  302. break;
  303. }
  304. }
  305. return need;
  306. }
  307. protected void setMessageId(String messageId)
  308. {
  309. this.messageId = messageId;
  310. }
  311. protected void setInReplyTo(String inReplyTo)
  312. {
  313. this.inReplyTo = inReplyTo;
  314. }
  315. protected void setUsers(List users)
  316. {
  317. this.users = users;
  318. }
  319. private String localhostProperty(boolean ssl)
  320. {
  321. return ssl 
  322. ? ConfigKeys.MAIL_SMTP_SSL_LOCALHOST
  323. : ConfigKeys.MAIL_SMTP_LOCALHOST;
  324. }
  325. private String authProperty(boolean ssl)
  326. {
  327. return ssl 
  328. ? ConfigKeys.MAIL_SMTP_SSL_AUTH
  329. : ConfigKeys.MAIL_SMTP_AUTH;
  330. }
  331. private String portProperty(boolean ssl)
  332. {
  333. return ssl 
  334. ? ConfigKeys.MAIL_SMTP_SSL_PORT
  335. : ConfigKeys.MAIL_SMTP_PORT;
  336. }
  337. private String hostProperty(boolean ssl)
  338. {
  339. return ssl 
  340. ? ConfigKeys.MAIL_SMTP_SSL_HOST
  341. : ConfigKeys.MAIL_SMTP_HOST;
  342. }
  343. }