1 24 package org.riotfamily.website.mail; 25 26 import java.io.StringWriter ; 27 28 import javax.servlet.http.HttpServletRequest ; 29 30 import org.springframework.beans.factory.InitializingBean; 31 import org.springframework.mail.MailSender; 32 import org.springframework.mail.SimpleMailMessage; 33 import org.springframework.util.Assert; 34 import org.springframework.web.bind.ServletRequestDataBinder; 35 import org.springframework.web.servlet.mvc.SimpleFormController; 36 37 import freemarker.template.Configuration; 38 import freemarker.template.Template; 39 40 44 public class SimpleMailFormController extends SimpleFormController 45 implements InitializingBean { 46 47 private String to; 48 49 private String [] bcc; 50 51 private String from; 52 53 private String subject; 54 55 private MailSender mailSender; 56 57 private Configuration freemarkerConfig; 58 59 private String mailTemplateName; 60 61 private String [] requiredFields; 62 63 64 public SimpleMailFormController() { 65 setCommandClass(MailForm.class); 66 } 67 68 public void setTo(String to) { 69 this.to = to; 70 } 71 72 public void setBcc(String [] bcc) { 73 this.bcc = bcc; 74 } 75 76 public void setFrom(String from) { 77 this.from = from; 78 } 79 80 public void setSubject(String subject) { 81 this.subject = subject; 82 } 83 84 public void setMailSender(MailSender mailSender) { 85 this.mailSender = mailSender; 86 } 87 88 public void setFreemarkerConfig(Configuration freemarkerConfig) { 89 this.freemarkerConfig = freemarkerConfig; 90 } 91 92 public void setMailTemplateName(String mailTemplateName) { 93 this.mailTemplateName = mailTemplateName; 94 } 95 96 public void setRequiredFields(String [] requiredFields) { 97 this.requiredFields = requiredFields; 98 } 99 100 public void afterPropertiesSet() throws Exception { 101 Assert.notNull(to); 102 Assert.notNull(mailSender); 103 Assert.notNull(freemarkerConfig); 104 Assert.notNull(mailTemplateName); 105 } 106 107 protected void initBinder(HttpServletRequest request, 108 ServletRequestDataBinder binder) throws Exception { 109 110 binder.setRequiredFields(requiredFields); 111 } 112 113 protected void doSubmitAction(Object command) throws Exception { 114 Template template = freemarkerConfig.getTemplate(mailTemplateName); 115 116 StringWriter mailTextWriter = new StringWriter (); 117 template.process(command, mailTextWriter); 118 119 SimpleMailMessage mail = new SimpleMailMessage(); 120 mail.setTo(to); 121 mail.setBcc(bcc); 122 mail.setFrom(from); 123 mail.setSubject(subject); 124 mail.setText(mailTextWriter.toString()); 125 prepareMail(mail, command); 126 mailSender.send(mail); 127 } 128 129 133 protected void prepareMail(SimpleMailMessage mail, Object command) { 134 } 135 136 } 137 | Popular Tags |