diff --git a/webapp/build.xml b/webapp/build.xml index 1f2c673a1..41b3269c7 100644 --- a/webapp/build.xml +++ b/webapp/build.xml @@ -108,8 +108,6 @@ deploy - Deploy the application directly into the Tomcat webapps directory. message="${deploy.properties.file} must contain a value for vitro.home.directory" /> - 0; - } - - @Override - public void init() { - smtpHost = ConfigurationProperties.getBean(getServletContext()) - .getProperty(SMTPHOST_PROPERTY, ""); - if (smtpHost.isEmpty()) { - log.debug("No Vitro.smtpHost specified"); - } else { - log.debug("Found Vitro.smtpHost value of " + smtpHost); - } - } - @Override public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { @@ -69,9 +49,9 @@ public class ContactMailServlet extends VitroHttpServlet { String statusMsg = null; // holds the error status - if (smtpHost==null || smtpHost.equals("")){ - statusMsg = "This application has not yet been configured to send mail " + - "-- smtp host has not been identified in the Configuration Properties file."; + if (!FreemarkerEmailFactory.isConfigured(vreq)) { + statusMsg = "This application has not yet been configured to send mail. " + + "Email properties must be specified in the configuration properties file."; redirectToError(response, statusMsg); return; } @@ -166,10 +146,7 @@ public class ContactMailServlet extends VitroHttpServlet { .getRealPath(EMAIL_BACKUP_FILE_PATH),true)); //autoflush writeBackupCopy(outFile, msgText, spamReason); - // Set the smtp host - Properties props = System.getProperties(); - props.put("mail.smtp.host", smtpHost); - Session s = Session.getDefaultInstance(props,null); // was Session.getInstance(props,null); + Session s = FreemarkerEmailFactory.getEmailSession(vreq); //s.setDebug(true); try { diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/MailUsersServlet.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/MailUsersServlet.java index b016b176f..351f10921 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/MailUsersServlet.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/MailUsersServlet.java @@ -6,7 +6,6 @@ import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.List; -import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; @@ -23,28 +22,15 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; import edu.cornell.mannlib.vitro.webapp.dao.UserDao; +import edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailFactory; public class MailUsersServlet extends VitroHttpServlet { private static final Log log = LogFactory.getLog(MailUsersServlet.class); public static HttpServletRequest request; public static HttpServletRequest response; - private static String smtpHost = ""; - // private static final Log log = LogFactory.getLog(ContactMailServlet.class.getName()); - @Override - public void init() { - smtpHost = ConfigurationProperties.getBean(getServletContext()) - .getProperty(ContactMailServlet.SMTPHOST_PROPERTY, ""); - if (smtpHost.isEmpty()) { - log.debug("No Vitro.smtpHost specified"); - } else { - log.debug("Found Vitro.smtpHost value of " + smtpHost); - } - } - @Override public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { @@ -54,9 +40,9 @@ public class MailUsersServlet extends VitroHttpServlet { String errpage = "/contact_err.jsp"; String status = null; // holds the error status - if (smtpHost==null || smtpHost.equals("")){ - status = "This application has not yet been configured to send mail " + - "-- smtp host has not been identified in the Configuration Properties file."; + if (!FreemarkerEmailFactory.isConfigured(vreq)) { + status = "This application has not yet been configured to send mail. " + + "Email properties must be specified in the configuration properties file."; response.sendRedirect( "test?bodyJsp=" + errpage + "&ERR=" + status ); return; } @@ -162,10 +148,8 @@ public class MailUsersServlet extends VitroHttpServlet { outFile.flush(); // outFile.close(); */ - // Set the smtp host - Properties props = System.getProperties(); - props.put("mail.smtp.host", smtpHost); - Session s = Session.getDefaultInstance(props,null); // was Session.getInstance(props,null); + + Session s = FreemarkerEmailFactory.getEmailSession(vreq); //s.setDebug(true); try { // Construct the message diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/UserMailController.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/UserMailController.java index ce55a1c6c..b022c4de6 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/UserMailController.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/UserMailController.java @@ -10,6 +10,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean; +import edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailFactory; /** * Controller for comments ("contact us") page @@ -30,11 +31,12 @@ public class UserMailController extends VitroHttpServlet{ VitroRequest vreq = new VitroRequest(request); try { //this try block passes any errors to error.jsp - if (!ContactMailServlet.isSmtpHostConfigured(request)) { + if (!FreemarkerEmailFactory.isConfigured(request)) { request.setAttribute("title", "Mail All Users Form"); request.setAttribute("bodyJsp", "/contact_err.jsp");// <<< this is where the body gets set - request.setAttribute("ERR","This application has not yet been configured to send mail -- " + - "smtp host has not been specified in the configuration properties file."); + request.setAttribute("ERR", + "This application has not yet been configured to send mail. " + + "Email properties must be specified in the configuration properties file."); RequestDispatcher errd = request.getRequestDispatcher(Controllers.BASIC_JSP); errd.forward(request, response); } diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ContactFormController.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ContactFormController.java index c18ef0bde..eb5f34180 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ContactFormController.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ContactFormController.java @@ -10,10 +10,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean; -import edu.cornell.mannlib.vitro.webapp.controller.ContactMailServlet; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; +import edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailFactory; /** * Controller for comments ("contact us") page @@ -40,10 +40,10 @@ public class ContactFormController extends FreemarkerHttpServlet { String templateName; Map body = new HashMap(); - if (!ContactMailServlet.isSmtpHostConfigured(vreq)) { + if (!FreemarkerEmailFactory.isConfigured(vreq)) { body.put("errorMessage", "This application has not yet been configured to send mail. " + - "An smtp host has not been specified in the configuration properties file."); + "Email properties must be specified in the configuration properties file."); templateName = TEMPLATE_ERROR; } diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ContactMailController.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ContactMailController.java index 2ddd62022..b7dc229d2 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ContactMailController.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ContactMailController.java @@ -10,7 +10,6 @@ import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; -import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; @@ -26,12 +25,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean; -import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; -import edu.cornell.mannlib.vitro.webapp.controller.ContactMailServlet; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.TemplateProcessingHelper.TemplateProcessingException; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; +import edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailFactory; import freemarker.template.Configuration; public class ContactMailController extends FreemarkerHttpServlet { @@ -51,19 +49,6 @@ public class ContactMailController extends FreemarkerHttpServlet { private final static String TEMPLATE_BACKUP = "contactForm-backup.ftl"; private final static String TEMPLATE_ERROR = "contactForm-error.ftl"; - private static String smtpHost = ""; - - @Override - public void init() { - smtpHost = ConfigurationProperties.getBean(getServletContext()) - .getProperty(ContactMailServlet.SMTPHOST_PROPERTY, ""); - if (smtpHost.isEmpty()) { - log.debug("No Vitro.smtpHost specified"); - } else { - log.debug("Found Vitro.smtpHost value of " + smtpHost); - } - } - @Override protected String getTitle(String siteName, VitroRequest vreq) { return siteName + " Feedback Form"; @@ -80,10 +65,10 @@ public class ContactMailController extends FreemarkerHttpServlet { String statusMsg = null; // holds the error status - if (smtpHost.isEmpty()) { + if (!FreemarkerEmailFactory.isConfigured(vreq)) { body.put("errorMessage", "This application has not yet been configured to send mail. " + - "An smtp host has not been specified in the configuration properties file."); + "Email properties must be specified in the configuration properties file."); templateName = TEMPLATE_ERROR; } @@ -172,11 +157,7 @@ public class ContactMailController extends FreemarkerHttpServlet { PrintWriter outFile = new PrintWriter(fw); writeBackupCopy(outFile, msgText, spamReason, config, vreq); - // Set the smtp host - Properties props = System.getProperties(); - props.put("mail.smtp.host", smtpHost); - Session s = Session.getDefaultInstance(props,null); // was Session.getInstance(props,null); - //s.setDebug(true); + Session s = FreemarkerEmailFactory.getEmailSession(vreq); try { if (spamReason == null) { diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/FreemarkerHttpServlet.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/FreemarkerHttpServlet.java index 046a13268..e4a1dcf15 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/FreemarkerHttpServlet.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/FreemarkerHttpServlet.java @@ -33,6 +33,7 @@ import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.Rdf import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.RedirectResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; +import edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailFactory; import edu.cornell.mannlib.vitro.webapp.web.templatemodels.Tags; import edu.cornell.mannlib.vitro.webapp.web.templatemodels.User; import edu.cornell.mannlib.vitro.webapp.web.templatemodels.menu.MainMenu; @@ -247,7 +248,7 @@ public class FreemarkerHttpServlet extends VitroHttpServlet { urls.put("base", UrlBuilder.contextPath); urls.put("about", urlBuilder.getPortalUrl(Route.ABOUT)); - if (ContactMailServlet.isSmtpHostConfigured(vreq)) { + if (FreemarkerEmailFactory.isConfigured(vreq)) { urls.put("contact", urlBuilder.getPortalUrl(Route.CONTACT)); } urls.put("search", urlBuilder.getPortalUrl(Route.SEARCH)); diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/email/FreemarkerEmailFactory.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/email/FreemarkerEmailFactory.java new file mode 100644 index 000000000..8eaac0efb --- /dev/null +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/email/FreemarkerEmailFactory.java @@ -0,0 +1,178 @@ +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ + +package edu.cornell.mannlib.vitro.webapp.email; + +import java.util.Properties; + +import javax.mail.Session; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; +import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; +import edu.cornell.mannlib.vitro.webapp.servlet.setup.AbortStartup; + +/** + * A factory that creates Freemarker-based email messages. + * + * Client code should call isConfigured(), to be sure that the required email + * properties have been provided. If isConfigured() returns false, the client + * code should respond accordingly. + * + * On the other hand, if the configuration properties are provided, but are + * syntactically invalid, an exception is thrown and startup is aborted. + */ +public class FreemarkerEmailFactory { + private static final Log log = LogFactory + .getLog(FreemarkerEmailFactory.class); + + public static final String SMTP_HOST_PROPERTY = "email.smtpHost"; + public static final String REPLY_TO_PROPERTY = "email.replyTo"; + + private static final String ATTRIBUTE_NAME = FreemarkerEmailFactory.class + .getName(); + + // ---------------------------------------------------------------------- + // static methods + // ---------------------------------------------------------------------- + + public static FreemarkerEmailMessage createNewMessage(VitroRequest vreq) { + if (!isConfigured(vreq)) { + throw new IllegalStateException("Email factory is not configured."); + } + + FreemarkerEmailFactory factory = getFactory(vreq); + return new FreemarkerEmailMessage(vreq, factory.getEmailSession(), + factory.getReplyToAddress()); + } + + public static boolean isConfigured(HttpServletRequest req) { + FreemarkerEmailFactory factory = getFactory(req); + return (factory != null) && (factory.isConfigured()); + } + + /** + * Client code that does not use the FreemarkerEmailFactory can still use + * it's Email Session. + */ + public static Session getEmailSession(HttpServletRequest req) { + if (!isConfigured(req)) { + throw new IllegalStateException("Email factory is not configured."); + } + return getFactory(req).getEmailSession(); + } + + private static FreemarkerEmailFactory getFactory(HttpServletRequest req) { + ServletContext ctx = req.getSession().getServletContext(); + return (FreemarkerEmailFactory) ctx.getAttribute(ATTRIBUTE_NAME); + } + + // ---------------------------------------------------------------------- + // The factory + // ---------------------------------------------------------------------- + + private final String smtpHost; + private final InternetAddress replyToAddress; + private final Session emailSession; + + public FreemarkerEmailFactory(ServletContext ctx) { + this.smtpHost = getSmtpHostFromConfig(ctx); + this.replyToAddress = getReplyToAddressFromConfig(ctx); + this.emailSession = createEmailSession(this.smtpHost); + } + + boolean isConfigured() { + return (!smtpHost.isEmpty()) && (replyToAddress != null); + } + + InternetAddress getReplyToAddress() { + return replyToAddress; + } + + Session getEmailSession() { + return emailSession; + } + + private String getSmtpHostFromConfig(ServletContext ctx) { + ConfigurationProperties config = ConfigurationProperties.getBean(ctx); + String hostName = config.getProperty(SMTP_HOST_PROPERTY, ""); + if (hostName.isEmpty()) { + log.info("Configuration property for '" + SMTP_HOST_PROPERTY + + "' is empty: email is disabled."); + } + return hostName; + } + + private InternetAddress getReplyToAddressFromConfig(ServletContext ctx) { + ConfigurationProperties config = ConfigurationProperties.getBean(ctx); + String rawAddress = config.getProperty(REPLY_TO_PROPERTY, ""); + if (rawAddress.isEmpty()) { + log.info("Configuration property for '" + REPLY_TO_PROPERTY + + "' is empty: email is disabled."); + return null; + } + + try { + InternetAddress[] addresses = InternetAddress.parse(rawAddress, + false); + if (addresses.length == 0) { + throw new IllegalStateException( + "No Reply-To address configured in '" + + REPLY_TO_PROPERTY + "'"); + } else if (addresses.length > 1) { + throw new IllegalStateException( + "More than one Reply-To address configured in '" + + REPLY_TO_PROPERTY + "'"); + } else { + return addresses[0]; + } + } catch (AddressException e) { + throw new IllegalStateException( + "Error while parsing Reply-To address configured in '" + + REPLY_TO_PROPERTY + "'", e); + } + } + + private Session createEmailSession(String hostName) { + Properties props = new Properties(System.getProperties()); + props.put("mail.smtp.host", hostName); + return Session.getDefaultInstance(props, null); + } + + // ---------------------------------------------------------------------- + // Setup class + // ---------------------------------------------------------------------- + + public static class Setup implements ServletContextListener { + @Override + public void contextInitialized(ServletContextEvent sce) { + ServletContext ctx = sce.getServletContext(); + + if (AbortStartup.isStartupAborted(ctx)) { + return; + } + + try { + ctx.setAttribute(ATTRIBUTE_NAME, + new FreemarkerEmailFactory(ctx)); + } catch (Exception e) { + log.error(e, e); + AbortStartup.abortStartup(ctx); + throw new RuntimeException(e); + } + } + + @Override + public void contextDestroyed(ServletContextEvent sce) { + sce.getServletContext().removeAttribute(ATTRIBUTE_NAME); + } + } + +} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/email/FreemarkerEmailMessage.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/email/FreemarkerEmailMessage.java new file mode 100644 index 000000000..3bc9115cf --- /dev/null +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/email/FreemarkerEmailMessage.java @@ -0,0 +1,244 @@ +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ + +package edu.cornell.mannlib.vitro.webapp.email; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.mail.Address; +import javax.mail.Message; +import javax.mail.Message.RecipientType; +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.cornell.mannlib.vitro.webapp.controller.freemarker.TemplateProcessingHelper; +import edu.cornell.mannlib.vitro.webapp.controller.freemarker.TemplateProcessingHelper.TemplateProcessingException; +import freemarker.template.Configuration; + +/** + * A framework that makes it simpler to send email messages with a body built + * from a Freemarker template. + * + * In fact, the body can be plain text from a template, HTML from a template, or + * both. + */ +public class FreemarkerEmailMessage { + private static final Log log = LogFactory + .getLog(FreemarkerEmailMessage.class); + + private static final String ATTRIBUTE_NAME = "freemarkerConfig"; + + private final HttpServletRequest req; + private final Session session; + private final Configuration config; + private final ServletContext ctx; + + private final List recipients = new ArrayList(); + private final InternetAddress replyToAddress; + + private InternetAddress fromAddress = null; + private String subject = ""; + private String htmlTemplateName; + private String textTemplateName; + private Map bodyMap = Collections.emptyMap(); + + /** + * Package access - should only be created by the factory. + */ + FreemarkerEmailMessage(HttpServletRequest req, Session session, + InternetAddress replyToAddress) { + this.req = req; + this.session = session; + this.replyToAddress = replyToAddress; + + this.ctx = req.getSession().getServletContext(); + + Object o = req.getAttribute(ATTRIBUTE_NAME); + if (!(o instanceof Configuration)) { + String oClass = (o == null) ? "null" : o.getClass().getName(); + + throw new IllegalStateException( + "Request does not contain a Configuration at '" + + ATTRIBUTE_NAME + "': " + oClass); + } + this.config = (Configuration) o; + } + + public void addRecipient(RecipientType type, String emailAddress) { + if (type == null) { + throw new NullPointerException("type may not be null."); + } + if (emailAddress == null) { + log.warn("recipient type was '" + type + + "', but email address was null."); + return; + } + + try { + recipients.add(new Recipient(type, emailAddress)); + } catch (AddressException e) { + log.warn("invalid recipient address: " + type + ", '" + + emailAddress + "'"); + return; + } + } + + public void addRecipient(RecipientType type, String emailAddress, + String personalName) { + if (personalName == null) { + addRecipient(type, emailAddress); + } + if (type == null) { + throw new NullPointerException("type may not be null."); + } + if (emailAddress == null) { + log.warn("recipient type was '" + type + + "', but email address was null."); + return; + } + + try { + recipients.add(new Recipient(type, emailAddress, personalName)); + } catch (AddressException e) { + log.warn("invalid recipient address: " + type + ", '" + + emailAddress + "', personal name '" + personalName + "'"); + return; + } catch (UnsupportedEncodingException e) { + log.warn("invalid recipient address: " + type + ", '" + + emailAddress + "', personal name '" + personalName + "'"); + return; + } + } + + public void setSubject(String subject) { + this.subject = nonNull(subject, ""); + } + + public void setHtmlTemplate(String templateName) { + this.htmlTemplateName = nonNull(templateName, ""); + } + + public void setTextTemplate(String templateName) { + this.textTemplateName = nonNull(templateName, ""); + } + + public void setBodyMap(Map body) { + if (body == null) { + this.bodyMap = Collections.emptyMap(); + } else { + this.bodyMap = Collections + .unmodifiableMap(new HashMap(body)); + } + } + + public void send() { + String textBody = figureMessageBody(textTemplateName); + String htmlBody = figureMessageBody(htmlTemplateName); + + try { + MimeMessage msg = new MimeMessage(session); + msg.setReplyTo(new Address[] { replyToAddress }); + + if (fromAddress == null) { + msg.addFrom(new Address[] { replyToAddress }); + } else { + msg.addFrom(new Address[] { fromAddress }); + } + + for (Recipient recipient : recipients) { + msg.addRecipient(recipient.type, recipient.address); + } + + msg.setSubject(subject); + + if (textBody.isEmpty()) { + if (htmlBody.isEmpty()) { + log.error("Message has neither text body nor HTML body"); + } else { + msg.setContent(htmlBody, "text/html"); + } + } else { + if (htmlBody.isEmpty()) { + msg.setContent(textBody, "text/plain"); + } else { + MimeMultipart content = new MimeMultipart("alternative"); + addBodyPart(content, textBody, "text/plain"); + addBodyPart(content, htmlBody, "text/html"); + msg.setContent(content); + } + } + + msg.setSentDate(new Date()); + + Transport.send(msg); + + } catch (MessagingException e) { + log.error("Failed to send message.", e); + } + } + + /** + * Process the template. If there is no template name or if there is a + * problem with the process, return an empty string. + */ + private String figureMessageBody(String templateName) { + if (templateName.isEmpty()) { + return ""; + } + + try { + TemplateProcessingHelper helper = new TemplateProcessingHelper( + config, req, ctx); + return helper.processTemplate(templateName, bodyMap).toString(); + } catch (TemplateProcessingException e) { + log.warn("Exception while processing email template '" + + templateName + "'", e); + return ""; + } + } + + private void addBodyPart(MimeMultipart content, String textBody, String type) + throws MessagingException { + MimeBodyPart bodyPart = new MimeBodyPart(); + bodyPart.setContent(textBody, type); + content.addBodyPart(bodyPart); + } + + private T nonNull(T value, T defaultValue) { + return (value == null) ? defaultValue : value; + } + + private static class Recipient { + final Message.RecipientType type; + final InternetAddress address; + + public Recipient(RecipientType type, String address) + throws AddressException { + this.type = type; + this.address = new InternetAddress(address); + } + + public Recipient(RecipientType type, String address, String personalName) + throws AddressException, UnsupportedEncodingException { + this.type = type; + this.address = new InternetAddress(address, personalName); + } + } + +} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/utils/MailUtil.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/utils/MailUtil.java index ec520c5aa..f0c2bece0 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/utils/MailUtil.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/utils/MailUtil.java @@ -4,7 +4,6 @@ package edu.cornell.mannlib.vitro.webapp.utils; import java.io.IOException; import java.util.Date; import java.util.List; -import java.util.Properties; import javax.mail.Message; import javax.mail.Session; @@ -16,28 +15,19 @@ import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; -import edu.cornell.mannlib.vitro.webapp.controller.ContactMailServlet; +import edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailFactory; public class MailUtil { private static final Log log = LogFactory.getLog(MailUtil.class); - - private String smtpHost = ""; + private final HttpServletRequest req; public MailUtil(HttpServletRequest req) { - smtpHost = ConfigurationProperties.getBean(req) - .getProperty(ContactMailServlet.SMTPHOST_PROPERTY, ""); - if (smtpHost.isEmpty()) { - log.debug("No Vitro.smtpHost specified"); - } else { - log.debug("Found Vitro.smtpHost value of " + smtpHost); - } + this.req = req; } public void sendMessage(String messageText, String subject, String from, String to, List deliverToArray) throws IOException{ - Properties props = System.getProperties(); - props.put("mail.smtp.host", smtpHost); - Session s = Session.getDefaultInstance(props,null); + + Session s = FreemarkerEmailFactory.getEmailSession(req); try{