Java Code Examples for org.springframework.ui.velocity.VelocityEngineUtils

The following examples show how to use org.springframework.ui.velocity.VelocityEngineUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Project   Source File: SpitterMailServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
* <p>描述:采用Velocity模板的富文本email</p>
* @param to
* @param spittle
* @throws MessagingException
 */
public void sendRichEmailWithVelocity(String to, Spittle spittle) throws MessagingException {
	MimeMessage message = mailSender.createMimeMessage();
	MimeMessageHelper helper = new MimeMessageHelper(message, true);
	String spitterName = spittle.getSpitter().getFullName();
	helper.setFrom("[email protected]");
	helper.setTo(to);
	helper.setSubject("New spittle from " + spitterName);
	
	Map<String, Object> model = new HashMap<String, Object>();
	model.put("spitterName", spitterName);
	model.put("spittleText", spittle.getText());
	String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
			"emailTemplate.vm", "UTF-8", model);
	
	helper.setText(emailText, true);
	ClassPathResource couponImage = new ClassPathResource("/collateral/coupon.jpg");
	helper.addInline("spitterLogo", couponImage);
	mailSender.send(message);
}
 
Example 2
@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()));
}
 
Example 3
Source Project: olat   Source File: MailServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 4
Source Project: olat   Source File: MailServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 5
Source Project: olat   Source File: MailServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void sendMailWithAttachments(final TemplateWithAttachmentMailTO template) throws MailException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

            message.addTo(template.getToMailAddress());
            message.setFrom(template.getFromMailAddress());
            message.setSubject(template.getSubject());
            if (template.hasCcMailAddress()) {
                message.setCc(template.getCcMailAddress());
            }
            if (template.hasReplyTo()) {
                message.setReplyTo(template.getReplyTo());
            }

            // add attachments if any
            List<File> attachments = template.getAttachments();
            for (File file : attachments) {
                message.addAttachment(file.getName(), file);
            }

            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template.getTemplateLocation(), template.getTemplateProperties());
            message.setText(text, true);
            message.setValidateAddresses(true);
        }
    };
    this.mailSender.send(preparator);
}
 
Example 6
Source Project: podcastpedia-web   Source File: EmailNotificationServiceImpl.java    License: MIT License 6 votes vote down vote up
public void sendContactNotification(final ContactForm contactForm) {
      MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @SuppressWarnings({ "rawtypes", "unchecked" })
		public void prepare(MimeMessage mimeMessage) throws Exception {
             MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
             message.setTo(configService.getValue("EMAIL_TO_CONTACT_MESSAGE"));
             message.setBcc("[email protected]");
             message.setFrom(new InternetAddress(contactForm.getEmail()));
             message.setSubject("New contact message " + contactForm.getTopic());
             message.setReplyTo(contactForm.getEmail());
             message.setSentDate(new Date());
             Map model = new HashMap();	             
             model.put("newMessage", contactForm);
             
             String text = VelocityEngineUtils.mergeTemplateIntoString(
                velocityEngine, "velocity/newContactMessageToAdmin.vm", "UTF-8", model);
             message.setText(text, true);
          }
       };
       this.mailSender.send(preparator);	  
}
 
Example 7
Source Project: podcastpedia-web   Source File: EmailNotificationServiceImpl.java    License: MIT License 6 votes vote down vote up
public void sendSuggestPodcastNotification(final SuggestedPodcast suggestedPodcast) {
      MimeMessagePreparator preparator = new MimeMessagePreparator() {
	        @SuppressWarnings({ "rawtypes", "unchecked" })
			public void prepare(MimeMessage mimeMessage) throws Exception {
	             MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
	             message.setTo(configService.getValue("EMAIL_TO_SUGGEST_PODCAST"));
	             message.setBcc("[email protected]");
	             message.setFrom(new InternetAddress(suggestedPodcast.getEmail()) );
	             message.setSubject("New suggested podcast");
	             message.setSentDate(new Date());
	             Map model = new HashMap();	             
	             model.put("newPodcast", suggestedPodcast);		             
	             String text = VelocityEngineUtils.mergeTemplateIntoString(
	                velocityEngine, "velocity/suggestPodcastNotificationMessage.vm", "UTF-8", model);
	             message.setText(text, true);
	          }
	       };
	       mailSender.send(preparator);			
}
 
Example 8
Source Project: mumu   Source File: SysIforgetController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 发送邮箱验证码
 * @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","邮箱发送失败!");
}
 
Example 9
Source Project: iotplatform   Source File: DefaultMailService.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 10
@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()));
}
 
Example 11
Source Project: spring-boot   Source File: SpringMailService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 12
Source Project: olat   Source File: MailServiceConcordionMock.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sendMailWithTemplate(final TemplateMailTO mailParameters) throws MailException {

    String emailBody = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailParameters.getTemplateLocation(), mailParameters.getTemplateProperties());
    userStatisticMap.put(getUserNameFromEmailAddress(mailParameters.getToMailAddress()), new UserNotifyStatistic(mailParameters.getToMailAddress(), true, emailBody,
            mailParameters.getSubject(), mailParameters.getFromMailAddress()));

}
 
Example 13
Source Project: olat   Source File: MailServiceConcordionMock.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sendMailWithTemplate(final TemplateMailTO mailParameters) throws MailException {

    String emailBody = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailParameters.getTemplateLocation(), mailParameters.getTemplateProperties());
    userStatisticMap.put(getUserNameFromEmailAddress(mailParameters.getToMailAddress()), new UserNotifyStatistic(mailParameters.getToMailAddress(), true, emailBody,
            mailParameters.getSubject(), mailParameters.getFromMailAddress()));

}
 
Example 14
/**
 * Set up MailMessage
 *
 * @return
 */
protected MailMessage constructMailMessage(final Map<String, Object> templateVariables) {
    MailMessage message = new MailMessage();
    // from...
    message.setFromAddress(mailService.getBatchMailingList());

    Collection<String> emailReceivers;
    message.setSubject(getEmailSubject());
    emailReceivers = getProdEmailReceivers();
    if (emailReceivers != null && !emailReceivers.isEmpty()) {
        setAndSplitEmailAddress(emailReceivers, message);
    }

    emailReceivers = getCcEmailReceivers();
    if (emailReceivers != null && !emailReceivers.isEmpty()) {
        setAndSplitCcEmailReceivers(emailReceivers, message);
    }

    emailReceivers = getBccEmailReceivers();
    if (emailReceivers != null && !emailReceivers.isEmpty()) {
        setAndSplitBccEmailReceivers(emailReceivers, message);
    }

    String body = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(), getTemplateUrl(), templateVariables);
    message.setMessage(body);
    return message;
}
 
Example 15
private MailMessage composeMailMessage(final MailMessageTemplate mailMessageTemplate, final User respondent,
        final String surveyLinkToken) {

    Map<String, Object> model = new HashMap<>();
    model.put("lastname", StringUtils.defaultIfBlank(respondent.getSurname(), ""));
    model.put("firstname", StringUtils.defaultIfBlank(respondent.getGivenNames(), ""));
    model.put("gender", respondent.getGender());
    model.put("link", "http://localhost:8080/questionaires-ui/token=" + surveyLinkToken);

    Language preferredLanguage = respondent.getPreferredLanguage();

    StringBuilder templateLocation = new StringBuilder().append(mailMessageTemplate.getId());
    if (preferredLanguage != null) {
        templateLocation.append("/");
        templateLocation.append(preferredLanguage);
    }
    VelocityEngine velocityEngine = velocityFactory.getObject();

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation.toString(), "UTF-8",
            model);

    MailMessageTemplateLanguageSettings languageSettings = mailMessageTemplate.getLanguageSettings();
    if (preferredLanguage != null && !preferredLanguage.equals(mailMessageTemplate.getLanguage())) {
        MailMessageTemplateTranslation preferedTranslation = mailMessageTemplate.getTranslations().get(
                preferredLanguage);
        if (preferedTranslation != null) {
            languageSettings = preferedTranslation.getLanguageSettings();
        }
    }
    MailMessage mailMessage = MailMessage.with().subject(languageSettings.getSubject()).to(respondent.getEmail())
            .replyTo(mailMessageTemplate.getReplyTo()).from(mailMessageTemplate.getFromAddress()).text(body)
            .build();
    return mailMessage;
}
 
Example 16
@Test
public void renderTemplateTest() {
    Map<String, Object> model = new HashMap<>();
    model.put("lastname", "test");
    model.put("firstname", "test");
    model.put("gender", "bot");
    model.put("link", "http://localhost:8080/questionaires-ui/token=1234");
    VelocityEngine velocityEngine = velocityFactory.getObject();
    String templateId = "55";
    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateId, "UTF-8", model);
    assertThat(body).contains("Estimado Sr. test");
}
 
Example 17
public String processTemplate(String templateName, Map model){
    return VelocityEngineUtils.mergeTemplateIntoString(
            velocityEngine, "templates/"+templateName, "UTF-8", model);
}
 
Example 18
/**
 * @see org.kuali.kfs.sys.service.KfsNotificationService#generateNotificationContent(java.lang.String, java.util.Map)
 */
@Override
public String generateNotificationContent(String template, Map<String, Object> model) {
    return VelocityEngineUtils.mergeTemplateIntoString(this.getVelocityEngine(), template, model);
}
 
Example 19
Source Project: iotplatform   Source File: DefaultMailService.java    License: Apache License 2.0 3 votes vote down vote up
@Override
public void sendActivationEmail(String activationLink, String email) throws IoTPException {

  String subject = messages.getMessage("activation.subject", null, Locale.US);

  Map<String, Object> model = new HashMap<String, Object>();
  model.put("activationLink", activationLink);
  model.put("targetEmail", email);

  String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine, "activation.vm", "UTF-8", model);

  sendMail(mailSender, mailFrom, email, subject, message);
}
 
Example 20
Source Project: iotplatform   Source File: DefaultMailService.java    License: Apache License 2.0 3 votes vote down vote up
@Override
public void sendAccountActivatedEmail(String loginLink, String email) throws IoTPException {

  String subject = messages.getMessage("account.activated.subject", null, Locale.US);

  Map<String, Object> model = new HashMap<String, Object>();
  model.put("loginLink", loginLink);
  model.put("targetEmail", email);

  String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine, "account.activated.vm", "UTF-8", model);

  sendMail(mailSender, mailFrom, email, subject, message);
}
 
Example 21
Source Project: iotplatform   Source File: DefaultMailService.java    License: Apache License 2.0 3 votes vote down vote up
@Override
public void sendResetPasswordEmail(String passwordResetLink, String email) throws IoTPException {

  String subject = messages.getMessage("reset.password.subject", null, Locale.US);

  Map<String, Object> model = new HashMap<String, Object>();
  model.put("passwordResetLink", passwordResetLink);
  model.put("targetEmail", email);

  String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine, "reset.password.vm", "UTF-8", model);

  sendMail(mailSender, mailFrom, email, subject, message);
}
 
Example 22
Source Project: iotplatform   Source File: DefaultMailService.java    License: Apache License 2.0 3 votes vote down vote up
@Override
public void sendPasswordWasResetEmail(String loginLink, String email) throws IoTPException {

  String subject = messages.getMessage("password.was.reset.subject", null, Locale.US);

  Map<String, Object> model = new HashMap<String, Object>();
  model.put("loginLink", loginLink);
  model.put("targetEmail", email);

  String message = VelocityEngineUtils.mergeTemplateIntoString(this.engine, "password.was.reset.vm", "UTF-8", model);

  sendMail(mailSender, mailFrom, email, subject, message);
}