1 package org.apache.turbine.util.velocity; 2 3 18 19 import java.net.URL ; 20 21 import java.util.Hashtable ; 22 23 import javax.mail.MessagingException ; 24 25 import org.apache.commons.lang.StringUtils; 26 27 import org.apache.commons.logging.Log; 28 import org.apache.commons.logging.LogFactory; 29 30 import org.apache.commons.mail.HtmlEmail; 31 32 import org.apache.turbine.Turbine; 33 import org.apache.turbine.TurbineConstants; 34 import org.apache.turbine.services.velocity.TurbineVelocity; 35 import org.apache.turbine.util.RunData; 36 37 import org.apache.velocity.context.Context; 38 39 83 public class VelocityHtmlEmail extends HtmlEmail 84 { 85 86 private static Log log = LogFactory.getLog(VelocityHtmlEmail.class); 87 88 92 private String htmlTemplate = null; 93 94 98 private String textTemplate = null; 99 100 101 private Context context = null; 102 103 104 private Hashtable embmap = null; 105 106 107 private String mailServer; 108 109 114 public VelocityHtmlEmail(RunData data) 115 { 116 this.context = TurbineVelocity.getContext(data); 117 embmap = new Hashtable (); 118 } 119 120 125 public VelocityHtmlEmail(Context context) 126 { 127 this.context = context; 128 embmap = new Hashtable (); 129 } 130 131 139 public VelocityHtmlEmail setHtmlTemplate(String template) 140 { 141 this.htmlTemplate = template; 142 return this; 143 } 144 145 153 public VelocityHtmlEmail setTextTemplate(String template) 154 { 155 this.textTemplate = template; 156 return this; 157 } 158 159 166 public void setMailServer(String serverAddress) 167 { 168 this.mailServer = serverAddress; 169 } 170 171 179 public String getMailServer() 180 { 181 return StringUtils.isNotEmpty(mailServer) ? mailServer 182 : Turbine.getConfiguration().getString( 183 TurbineConstants.MAIL_SERVER_KEY, 184 TurbineConstants.MAIL_SERVER_DEFAULT); 185 } 186 187 192 public void send() throws MessagingException 193 { 194 context.put("mail", this); 195 196 try 197 { 198 if (htmlTemplate != null) 199 { 200 setHtmlMsg( 201 TurbineVelocity.handleRequest(context, htmlTemplate)); 202 } 203 if (textTemplate != null) 204 { 205 setTextMsg( 206 TurbineVelocity.handleRequest(context, textTemplate)); 207 } 208 } 209 catch (Exception e) 210 { 211 throw new MessagingException ("Cannot parse velocity template", e); 212 } 213 setHostName(getMailServer()); 214 super.send(); 215 } 216 217 241 public String embed(String surl, String name) throws VelocityEmailException 242 { 243 String cid = ""; 244 try 245 { 246 URL url = new URL (surl); 247 cid = embed(url, name); 248 } 249 catch (Exception e) 250 { 251 log.error("cannot embed " + surl + ": ", e); 252 } 253 return cid; 254 } 255 256 263 public String getCid(String filename) 264 { 265 String cid = (String ) embmap.get(filename); 266 return "cid:" + cid; 267 } 268 269 } 270 | Popular Tags |