@Override public void sendEmail(final UserDTO user, String url) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(user.getEmail()); message.setSubject(SUBJECT); message.setFrom(EMAIL_FROM); // could be parameterized... Map model = new HashMap(); model.put("user", user); model.put("url", url); String text = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, "org/enricogiurin/sushibar/registration-confirmation.vm", model); message.setText(text, true); } }; this.emailSender.send(preparator); }
@Override public void sendMailWithTemplate(final TemplateMailTO mailParameters) throws MailException { MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(mailParameters.getToMailAddress()); message.setFrom(mailParameters.getFromMailAddress()); message.setSubject(mailParameters.getSubject()); if (mailParameters.hasCcMailAddress()) { message.setCc(mailParameters.getCcMailAddress()); } if (mailParameters.hasReplyTo()) { message.setReplyTo(mailParameters.getReplyTo()); } String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailParameters.getTemplateLocation(), mailParameters.getTemplateProperties()); log.debug("*** TEST text='" + text + "'"); message.setText(text, true); message.setValidateAddresses(true); } }; this.mailSender.send(preparator); }
@Test @SuppressWarnings("deprecation") public void velocityConfigurerWithCsvPathAndNonFileAccess() throws IOException, VelocityException { VelocityConfigurer vc = new VelocityConfigurer(); vc.setResourceLoaderPath("file:/mydir,file:/yourdir"); vc.setResourceLoader(new ResourceLoader() { @Override public Resource getResource(String location) { if ("file:/yourdir/test".equals(location)) { return new DescriptiveResource(""); } return new ByteArrayResource("test".getBytes(), "test"); } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } }); vc.setPreferFileSystemAccess(false); vc.afterPropertiesSet(); assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", Collections.emptyMap())); }
@Override public void sendActivation(User user) throws InvalidTokenException { if (user.getActivationToken() == null) { throw new InvalidTokenException("No activation token found for " + user.toString()); } Map<String, Object> model = getBaseModel(user); model.put("url", hostname + "#/activation/" + user.getUsername() + "/" + user.getActivationToken().getToken()); final String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "templates/sendActivation.vm", "UTF-8", model); MimeMessagePreparator preparator = mimeMessage -> { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); mimeMessage.setFrom(new InternetAddress(mailFromAddress)); mimeMessage.setSubject("Kanbanboard WGM Accountaktivierung"); mimeMessage.setText(body, "UTF-8", "html"); }; try { mailSender.send(preparator); log.info("Activation Mail sent to "+ user.getEmail()); } catch (MailException e) { log.error("Could not send activation mail to " + user.getEmail() + ". The error was :", e); } }
@Override public void sendPasswordReset(User user) throws InvalidTokenException { if (user.getPasswordResetToken() == null) { throw new InvalidTokenException("No password reset token found for " + user.toString()); } final Map<String, Object> model = getBaseModel(user); model.put("url", hostname + "#/reset/" + user.getUsername() + "/" + user.getPasswordResetToken().getToken()); final String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "templates/sendPasswordReset.vm", "UTF-8", model); MimeMessagePreparator preparator = mimeMessage -> { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); mimeMessage.setFrom(new InternetAddress(mailFromAddress)); mimeMessage.setSubject("Kanbanboard WGM Passwort Reset"); mimeMessage.setText(body, "UTF-8", "html"); }; try { mailSender.send(preparator); log.info("Reset Mail sent to {}", user.getEmail()); } catch (MailException e) { log.error("Could not send mail to " + user.getEmail() + ". The error was :", e); } }
/** * Sends e-mail using Velocity template for the body and the properties * passed in as Velocity variables. * * @param msg The e-mail message to be sent, except for the body. * @param hTemplateVariables Variables to use when processing the template. */ protected void send(SimpleMailMessage msg, String language, String template, Map<String, Object> hTemplateVariables) { LOG.info("Send email ..."); MimeMessagePreparator preparator = (MimeMessage mimeMessage) -> { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8"); message.setTo(msg.getTo()); message.setFrom(msg.getFrom()); message.setSubject(msg.getSubject()); String body = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, "/" + template + "." + language + ".vm", "UTF-8", hTemplateVariables); LOG.log(Level.INFO, "Body: {0}", body); message.setText(body, true); }; mailSender.send(preparator); LOG.log(Level.INFO, "Sender {0}", msg.getFrom()); LOG.log(Level.INFO, "Recipient {0}", msg.getTo()); }
/** * Render the http auth properties file to be used with openfire * * @param request * the request to use * @return the rendered properties */ public static String getOpenfireHttpAuthProperties(HttpServletRequest request) { // TODO change JSPs to VM and parse the http_auth.properties template VelocityEngine engine = ServiceLocator.findService(VelocityEngine.class); Map<String, Object> context = new HashMap<String, Object>(); context.put("defaultHost", ApplicationProperty.WEB_SERVER_HOST_NAME.getValue()); context.put("defaultPort", ApplicationProperty.WEB_HTTP_PORT.getValue()); context.put("internalHost", request.getServerName()); context.put("internalPort", request.getServerPort()); if (request.isSecure()) { context.put("internalProtocol", "https"); } else { context.put("internalProtocol", "http"); } context.put("defaultPortHttps", ApplicationProperty.WEB_HTTPS_PORT.getValue()); context.put("context", request.getContextPath()); String render = VelocityEngineUtils.mergeTemplateIntoString(engine, VELOCITY_TEMPLATE_HTTP_AUTH_PROPERTIES, context); return render; }
@Override public String buildMessageBody(EmailInfo info, Map<String,Object> props) { if (props == null) { props = new HashMap<String, Object>(); } if (props instanceof HashMap) { HashMap<String, Object> hashProps = (HashMap<String, Object>) props; @SuppressWarnings("unchecked") Map<String,Object> propsCopy = (Map<String, Object>) hashProps.clone(); if (additionalConfigItems != null) { propsCopy.putAll(additionalConfigItems); } return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, info.getEmailTemplate(), info.getEncoding(), propsCopy); } throw new IllegalArgumentException("Property map must be of type HashMap<String, Object>"); }
/** * Send a simple message based on a Velocity template. * * @param msg * the message to populate * @param templateName * the Velocity template to use (relative to classpath) * @param model * a map containing key/value pairs */ @SuppressWarnings("unchecked") public void sendMessage(SimpleMailMessage msg, String templateName, Map model) { String result = null; try { result = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, templateName, model); } catch (VelocityException e) { log.error(e.getMessage()); } msg.setText(result); send(msg); }
/** * Send a simple message based on a Velocity template. * @param msg the message to populate * @param templateName the Velocity template to use (relative to classpath) * @param model a map containing key/value pairs */ public void sendMessage(SimpleMailMessage msg, String templateName, Map model) { String result = null; try { result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, "UTF-8", model); } catch (VelocityException e) { e.printStackTrace(); log.error(e.getMessage()); } msg.setText(result); send(msg); }
@Override public void send(final SimpleMailMessage msg, final Map<String, Object> hTemplateVariables, final String templateFileName) { MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(msg.getTo()); message.setFrom(msg.getFrom()); message.setSubject(msg.getSubject()); String body = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, templateFileName, hTemplateVariables); //logger.info("body={}", body); message.setText(body, true); } }; mailSender.send(preparator); }
public void sendMail(Mail mail, Map<String, Object> model) throws MessagingException { //TODO: Deepak. not the perfect way to pull resources from the below code //but accordng to http://velocity.apache.org/engine/releases/velocity-1.7/developer-guide.html#resourceloaders //File resource handelers needs more config for which we don't have enough time. MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false,"utf-8"); helper.setSubject(mail.getSubject()); helper.setFrom(AppConstants.APP_EMAILID); for (MailReceiver mailReceiver : mail.getReceivers()) { model.put("_receiverFirstName", mailReceiver.firstName); model.put("_receiverLastName", mailReceiver.lastName); model.put("_receiverEmail", mailReceiver.email); model.put("_receiverImageUrl", mailReceiver.imageUrl); String mailBody = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "com/gendevs/bedrock/appengine/integration/mail/templates/" + mail.getTemplateName(), "UTF-8", model); mimeMessage.setContent(mailBody, mail.getContentType()); helper.setTo(mailReceiver.email); mailSender.send(mimeMessage); } }
public void sendMailWithTemplate(final TemplateMailTO mailParameters) throws MailException { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(mailParameters.getToMailAddress()); message.setFrom(mailParameters.getFromMailAddress()); message.setSubject(mailParameters.getSubject()); if (mailParameters.hasCcMailAddress()) { message.setCc(mailParameters.getCcMailAddress()); } if (mailParameters.hasReplyTo()) { message.setReplyTo(mailParameters.getReplyTo()); } String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailParameters.getTemplateLocation(), mailParameters.getTemplateProperties()); log.debug("*** TEST text='" + text + "'"); message.setText(text, true); message.setValidateAddresses(true); } }; this.mailSender.send(preparator); }
@Override public void sendTplLocationEmail(final String from, final List<String> to, final List<String> cc, final String subject, final String tplLocation, final Map<String, Object> model) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(to.toArray(new String[to.size()])); message.setCc(cc.toArray(new String[cc.size()])); message.setFrom(from); message.setSubject(subject); String tpl; tpl = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, tplLocation, "utf-8", model); message.setText(tpl, true); } }; JavaMailSenderImpl javaMailSenderImpl = (JavaMailSenderImpl) mailSender; javaMailSenderImpl.send(preparator); }
public String generateDataProvider() { Map<String, Object> model = new HashMap<>(); List<Config> configurations = openMRSConfigService.getConfigs().getConfigs(); if (configurations.isEmpty()) { // return null in case of no configurations - the provider won't get registered return null; } model.put("configurations", configurations); StringWriter writer = new StringWriter(); VelocityEngineUtils.mergeTemplate(velocityEngine, OPENMRS_TASK_DATA_PROVIDER, "UTF-8", model, writer); String providerJson = writer.toString(); LOGGER.trace("Generated the following tasks data provider: {}", providerJson); return providerJson; }
public void testVelocityEngineFactoryBeanWithNonFileResourceLoaderPath() throws Exception { VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean(); vefb.setResourceLoaderPath("file:/mydir"); vefb.setResourceLoader(new ResourceLoader() { @Override public Resource getResource(String location) { if (location.equals("file:/mydir") || location.equals("file:/mydir/test")) { return new ByteArrayResource("test".getBytes(), "test"); } try { return new UrlResource(location); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex.toString()); } } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } }); vefb.afterPropertiesSet(); assertThat(vefb.getObject(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vefb.getObject(); assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap())); }
public void testVelocityConfigurerWithCsvPathAndNonFileAccess() throws IOException, VelocityException { VelocityConfigurer vc = new VelocityConfigurer(); vc.setResourceLoaderPath("file:/mydir,file:/yourdir"); vc.setResourceLoader(new ResourceLoader() { @Override public Resource getResource(String location) { if ("file:/yourdir/test".equals(location)) { return new DescriptiveResource(""); } return new ByteArrayResource("test".getBytes(), "test"); } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } }); vc.setPreferFileSystemAccess(false); vc.afterPropertiesSet(); assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap())); }
public boolean sendConfirmMail(SBean bean, String action) { try { MimeMessage message = mailSender.createMimeMessage(); message.setSubject(getMessage("subscription.subject"), "UTF-8"); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(bean.getEmail().toLowerCase())); message.setFrom(new InternetAddress(getMessage("subscription.from"))); Map model = new HashMap(); model.put("subscribe_link", composeLink(bean, SubscriptionService.ACTION_SUBSCRIBE)); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/WEB-INF/templates/subscribe.vm", "UTF-8", model); message.setContent(text, "text/html;charset=utf-8"); this.mailSender.send(message); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
public boolean sendUpdatesMail(SBean bean, Map<String, List<String>> data) { try { MimeMessage message = mailSender.createMimeMessage(); message.setSubject(getMessage("subscription.subject"), "UTF-8"); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(bean.getEmail())); message.setFrom(new InternetAddress(getMessage("subscription.from"))); Map model = new HashMap(); model.put("edit_link", composeLink(bean, SubscriptionService.ACTION_UNSUBSCRIBE)); model.put("data", data); String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/WEB-INF/templates/updates.vm", "UTF-8", model); message.setContent(content, "text/html;charset=utf-8"); this.mailSender.send(message); return true; } catch (Exception e) { return false; } }
private EmailServiceTokenModel sendVerificationEmail(final EmailServiceTokenModel emailVerificationModel, final String emailSubject, final String velocityModel, final Map<String, String> resources) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_RELATED, "UTF-8"); messageHelper.setTo(emailVerificationModel.getEmailAddress()); messageHelper.setFrom(emailFromAddress); messageHelper.setReplyTo(emailReplyToAddress); messageHelper.setSubject(emailSubject); Map model = new HashMap(); model.put("model", emailVerificationModel); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityModel, model); messageHelper.setText(new String(text.getBytes(), "UTF-8"), true); for(String resourceIdentifier: resources.keySet()) { addInlineResource(messageHelper, resources.get(resourceIdentifier), resourceIdentifier); } } }; LOG.debug("Sending {} token to : {}",emailVerificationModel.getTokenType().toString(), emailVerificationModel.getEmailAddress()); this.mailSender.send(preparator); return emailVerificationModel; }
/** * Generates the mail message based on the file import status. * * @param importStatus The import status to generate file import mail message. * @return The file import mail message for the status. */ private String makeImportMailMessage(ImportStatus importStatus) { Map<String, Object> model = new HashMap<String, Object>(); model.put("importStatus", importStatus); model.put("dateTool", new DateTool()); model.put("mathTool", new MathTool()); model.put("numberTool", new NumberTool()); model.put("StringUtils", StringUtils.class); try { return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, fileImportMailTemplate, "utf-8", model); } catch (VelocityException ve) { logger.error("Error while making file import mail message", ve); // Use the log text instead... return logImportStatus(importStatus); } }
/** * @see com.johndeere.myjd.service.email.CreateEmail#createEmail(com.johndeere.myjd.service.email.model.EmailParams) * @param emailParams * Email params required for creating the email * @return the Email content */ @Override public EmailParams createEmail(EmailParams emailParams) { if (LOG.isInfoEnabled()) { LOG.info("Enter create Email"); } // Get the template Variables to be used */ Map<String, Object> hTemplateVariables = emailParams .getParamsMapHolder(); String emailBody = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, emailParams.getEmailTemplate(),"UTF-8", hTemplateVariables); if(LOG.isDebugEnabled()){ LOG.debug("Email body returned is : " + emailBody ); } emailParams.setEmailBody(emailBody); if(LOG.isDebugEnabled()){ LOG.debug("Exit Create Email " + emailParams); } return emailParams; }
private String geVelocityTemplateContent(Map<String, Object> model, String templateName) throws VelocityException { StringBuilder content = new StringBuilder(); try { content.append(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, "UTF-8", model)); return content.toString(); } catch (VelocityException e) { log.debug("Exception occured while processing velocity template: " + e.getMessage()); throw e; } }
/** * 发送邮箱验证码 * @param email 邮箱账号 * @param request * @return */ @ResponseBody @RequestMapping(value = "/sendEmail",method = RequestMethod.POST) public ResponseEntity sendEmail(String email, HttpServletRequest request){ if(email==null||!ValidateUtils.isEmail(email)){ return new ResponseEntity(400,"error","邮箱账号错误!"); } //发送注册邮件 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ request.getContextPath()+"/"; Map<String,Object> modelMap=new HashMap<String,Object>(); modelMap.put("USERNAME","baby慕慕"); modelMap.put("LOGOIMG",basePath+"resources/img/logo.png"); int verifyCode = RandomUtils.nextInt(100000, 999999); request.getSession().setAttribute("VERIFYCODE",String.valueOf(verifyCode)); modelMap.put("VERIFYCODE",verifyCode); modelMap.put("IFORGOTURL",basePath+"system/iforget"); modelMap.put("LOGINURL",basePath+"system/login"); modelMap.put("OFFICIALURL",basePath); String content= VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "tpl/verifyCodeEmail.html","UTF-8",modelMap); try { boolean sendSuccess=emailService.send(email,null,"baby慕慕开放平台-验证码找回密码",content); if(sendSuccess){ return new ResponseEntity(200,"success","验证码发送成功"); } } catch (EmailException e) { e.printStackTrace(); } return new ResponseEntity(400,"error","邮箱发送失败!"); }
/** * 发送邮箱验证码 * * @param email 邮箱账号 * @param request * @return */ @ResponseBody @RequestMapping(value = "/send", method = RequestMethod.POST) public ResponseEntity sendEmail(String email, HttpServletRequest request) { if (email == null || !ValidateUtils.isEmail(email)) { return new ResponseEntity(400, "error", "邮箱账号错误!"); } //发送注册邮件 String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; Map<String, Object> modelMap = new HashMap<String, Object>(); modelMap.put("USERNAME", "baby慕慕"); modelMap.put("LOGOIMG", basePath + "resources/portal/img/logo.png"); int verifyCode = RandomUtils.nextInt(100000, 999999); request.getSession().setAttribute("VERIFYCODE", String.valueOf(verifyCode)); modelMap.put("VERIFYCODE", verifyCode); modelMap.put("IFORGOTURL", basePath + "iforget"); modelMap.put("LOGINURL", basePath + "login"); modelMap.put("OFFICIALURL", basePath); String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "tpl/verifyCodeEmail.html", "UTF-8", modelMap); try { boolean sendSuccess = emailService.send(email, null, "baby慕慕开放平台-验证码找回密码", content); if (sendSuccess) { return new ResponseEntity(200, "success", "验证码发送成功"); } } catch (EmailException e) { e.printStackTrace(); } return new ResponseEntity(400, "error", "邮箱发送失败!"); }
private String getMessage(Notification notification, Map messageParameters) throws Exception { String messageVslFileName = L10nUtil.getNotificationMessageTemplate(Locales.NOTIFICATION, notification.getType().getMessageTemplateL10nKey()); if (messageVslFileName != null && messageVslFileName.length() > 0) { return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, messageVslFileName, messageParameters); } else { return null; } }
@Override public void sendTestMail(JsonNode jsonConfig, String email) throws IoTPException { JavaMailSenderImpl testMailSender = createMailSender(jsonConfig); String mailFrom = jsonConfig.get("mailFrom").asText(); String subject = messages.getMessage("test.message.subject", null, Locale.US); Map<String, Object> model = new HashMap<String, Object>(); model.put("targetEmail", email); String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine, "test.vm", "UTF-8", model); sendMail(testMailSender, mailFrom, email, subject, message); }
@Test @SuppressWarnings("deprecation") public void velocityEngineFactoryBeanWithNonFileResourceLoaderPath() throws Exception { VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean(); vefb.setResourceLoaderPath("file:/mydir"); vefb.setResourceLoader(new ResourceLoader() { @Override public Resource getResource(String location) { if (location.equals("file:/mydir") || location.equals("file:/mydir/test")) { return new ByteArrayResource("test".getBytes(), "test"); } try { return new UrlResource(location); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex.toString()); } } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } }); vefb.afterPropertiesSet(); assertThat(vefb.getObject(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vefb.getObject(); assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", Collections.emptyMap())); }
@Override public void sendTemplete(String address, String subject, String template, Map<String, Object> data) { data.put("domain", getDomain()); final String html = VelocityEngineUtils.mergeTemplateIntoString(emailEngine.getEngine(), template, "UTF-8", data); sendText(address, subject, html, true); }
private void remindUser(User user, List<Task> tasks) { MimeMessagePreparator preparator = mimeMessage -> { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); mimeMessage.setFrom(new InternetAddress(mailFromAddress)); StringBuilder sb = new StringBuilder(); sb.append("<ul>"); for (Task task : tasks) { sb.append("<li>").append(task.getCategory()).append(": ").append(task.getTitle()).append("</li>"); } sb.append("</ul>"); final String tasktext = sb.toString(); final Map<String, Object> model = getBaseModel(user); model.put("tasktext", tasktext); final String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "templates/sendReminder.vm", "UTF-8", model); mimeMessage.setSubject("Kanbanboard WGM Task Reminder"); mimeMessage.setText(body, "UTF-8", "html"); }; try { mailSender.send(preparator); log.info("Reminder Mail sent to {} containing {} tasks.", user.getEmail(), tasks.size()); } catch (MailException e) { log.error("Could not send mail to {}. The error was :", user.getEmail(), e); } }
/** * Velocity 模板发送邮件 html 格式 * * @param to * @param subject * @throws javax.mail.MessagingException */ public void sendMailVelocity(String from ,String[] to, String subject) throws MessagingException { //如果不是 html 格式,修改为 SimpleMailMessage MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.toString()); /** *邮件内容 */ helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); //模板内容 Map<String, Object> model = new HashMap<String, Object>(); model.put("firstName", "Yashwant"); model.put("lastName", "Chavan"); model.put("location", "china"); //创建动态 bean DynaBean dynaBean = new LazyDynaBean(); dynaBean.set("name", "It is name"); //simple dynaBean.set("gender", new Integer(1)); //simple //设置 bean 属性 // Velocity 工具类,实例可以直接放入 map ,在模板文件中直接使用 // 如日期格式化 $dateTool.format("yyyy-MM-dd",$info.issueTime) DateTool dateTool = new DateTool();//日期工具 NumberTool numberTool = new NumberTool();//数字工具 model.put("dateTool",dateTool); model.put("numberTool",numberTool); model.put("bean", dynaBean); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "./templates/velocity_template_email-newsletter.vm", StandardCharsets.UTF_8.toString(), model); helper.setText(text, true); mailSender.send(message); }
@Override public void run(String... args) throws Exception { Map<String, Object> model = new HashMap<String, Object>(); model.put("time", new Date()); model.put("message", this.message); System.out.println(VelocityEngineUtils.mergeTemplateIntoString(this.engine, "welcome.vm", "UTF-8", model)); }
@SuppressWarnings({ "rawtypes", "unchecked" }) public void sendForgotPassword(User user, String code) { Map model = new HashMap(); model.put("user", user); model.put("code", code); String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "templates/forgot_password.vm", "UTF-8", model); String subject = "Change password for RotaryLive"; sendEmail(user.getMember().getEmail(), subject, content, from ,false, true); }