我想知道在使用Velocity的Spring MVC应用程序中发送带有图像的电子邮件的最佳方法。
图像应该在应用程序中,可能与*.vm
模板位于同一位置(例如src/main/resources/templates
),不应使用绝对路径(例如C:\ App ...),这就是为什么我无法弄清楚如何做到这一点。
有什么建议吗?
您需要了解图片和电子邮件如何共同工作。在这方面我不是专家,但我认为有以下几种选择:
请查看org.springframework.mail.javamail.MimeMessageHelper。
使用Spring框架,你可以轻松地从文件系统或classpath(甚至jar包中)加载资源,而无需使用绝对路径。你应该使用Resource
及其实现,主要有FileSystemResource
和ClasspathResource
。
以下是一个示例:
Resource fileResource = new FileSystemResource("resources/templates");
加载后,您可以直接从资源实例中检索输入流。
此外,您可以将相对路径注入到具有类型为 Resource 的实例属性的 bean 中:
<bean id="mailer" class="test.Mailer">
<property name="templateResource" value="file:resource/templates" />
</bean>
虽然我不使用Velocity,但我通常会以这种方式加载模板,使用freemarker生成动态内容。一旦你加载了图片,你也可以将其附加到电子邮件中。
final Map<String, Object> model = new HashMap<String, Object>();
将模板中的图片链接添加到了模型中,然后使用model.put("urlLogo", urlLogo);
,最后使用VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "emailTemplates/template.vm", model);
。 - Martin Spa