1 package org.apache.turbine.util.velocity; 2 3 18 19 import javax.mail.MessagingException ; 20 21 import org.apache.commons.lang.StringUtils; 22 23 import org.apache.commons.logging.Log; 24 import org.apache.commons.logging.LogFactory; 25 26 import org.apache.commons.mail.SimpleEmail; 27 28 import org.apache.turbine.Turbine; 29 import org.apache.turbine.TurbineConstants; 30 import org.apache.turbine.services.velocity.TurbineVelocity; 31 32 import org.apache.velocity.context.Context; 33 34 103 public class VelocityEmail extends SimpleEmail 104 { 105 106 private static Log log = LogFactory.getLog(VelocityEmail.class); 107 108 109 private int wordWrap = 0; 110 111 112 private String mailServer; 113 114 115 private String template = null; 116 117 118 private Context context = null; 119 120 123 public VelocityEmail() 124 { 125 } 126 127 130 public VelocityEmail(Context context) 131 { 132 this.context = context; 133 } 134 135 144 public VelocityEmail setTo(String toName, String toEmail) 145 throws MessagingException 146 { 147 addTo(toEmail,toName); 148 return this; 149 } 150 151 159 public VelocityEmail setTemplate(String template) 160 { 161 this.template = template; 162 return this; 163 } 164 165 176 public VelocityEmail setWordWrap(int wordWrap) 177 { 178 this.wordWrap = wordWrap; 179 return this; 180 } 181 182 189 public VelocityEmail setContext(Context context) 190 { 191 this.context = context; 192 return this; 193 } 194 195 201 public Context getContext() 202 { 203 return this.context; 204 } 205 206 213 public void setMailServer(String serverAddress) 214 { 215 this.mailServer = serverAddress; 216 } 217 218 226 public String getMailServer() 227 { 228 return StringUtils.isNotEmpty(mailServer) ? mailServer 229 : Turbine.getConfiguration().getString( 230 TurbineConstants.MAIL_SERVER_KEY, 231 TurbineConstants.MAIL_SERVER_DEFAULT); 232 } 233 234 243 public void send() throws MessagingException 244 { 245 String body = null; 246 try 247 { 248 body = TurbineVelocity.handleRequest(context, template); 250 } 251 catch (Exception e) 252 { 253 throw new MessagingException ( 254 "Could not render velocitty template", e); 255 } 256 257 if (wordWrap > 0) 259 { 260 body = org.apache.turbine.util.StringUtils.wrapText(body, 261 System.getProperty("line.separator"), wordWrap); 262 } 263 264 setMsg(body); 265 setHostName(getMailServer()); 266 super.send(); 267 } 268 269 275 public String toString() 276 { 277 try 278 { 279 send(); 280 } 281 catch (Exception e) 282 { 283 log.error("VelocityEmail error", e); 284 } 285 return ""; 286 } 287 } 288 | Popular Tags |