我有一个用模板编写Java
的简单电子邮件程序,用于格式化发送电子邮件的数据,这些数据应该以格式显示。但是,它只是显示数据以及嵌入其中的标签,而不实际解析它们。Spring
Velocity
html
html
我在这里错过了什么吗?
电子邮件服务.java
public class EmailService {
private static final Log LOG = LogFactory.getLog(EmailService.class);
private static final String EMAIL_SUBJECT = ":: Risk Assessment Job Summary Results::";
private final MailSender mailSender;
private final String emailRecipientAddress;
private final String emailSenderAddress;
private static final String ERROR_MSG = "Error while sending notification email";
private final TemplateFactory velocityTemplateFactory;
private Template riskAssessmentJobResultSummaryTemplate;
public EmailService(MailSender mailSender, String emailRecipientAddress,
String emailSenderAddress, TemplateFactory velocityTemplateFactory) {
this.mailSender = mailSender;
this.emailRecipientAddress = emailRecipientAddress;
this.emailSenderAddress = emailSenderAddress;
this.velocityTemplateFactory = velocityTemplateFactory;
}
public void notify(String messageBody) {
JavaMailSender javaMailSender = (JavaMailSender)mailSender;
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message);
try {
mimeMessageHelper.setSubject(getHostname() + " - " + EMAIL_SUBJECT);
mimeMessageHelper.setTo(emailRecipientAddress);
mimeMessageHelper.setFrom(emailSenderAddress);
mimeMessageHelper.setText(getEmailContent(messageBody));
javaMailSender.send(message);
} catch (MailException e) {
throw new EmailSendException(ERROR_MSG, e);
} catch (MessagingException e) {
e.printStackTrace();
}
}
private static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "unknown host";
}
}
private String getEmailContent(String messageBody) {
try {
StringWriter stringWriter = new StringWriter();
this.riskAssessmentJobResultSummaryTemplate =
velocityTemplateFactory.create("velocity/risk-assessment-job-results-summary.vm");
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("hostname", getHostname());
velocityContext.put("messageBody", messageBody);
this.riskAssessmentJobResultSummaryTemplate.merge(velocityContext, stringWriter);
return stringWriter.toString();
} catch (IOException ex) {
LOG.error("Unable to read the email template", ex);
return null;
}
}
}
风险评估作业结果summary.vm
<h3>Summary report for Risk Assessment Job on ${hostname}:</h3>
<table style="border:none;">
<tr><td>${messageBody}</td></tr>
</table>
实际电子邮件输出:
<h3>Summary report for Risk Assessment Job on KOP-DBT0J12:</h3>
<table style="border:none;">
<tr><td>
TotalTxPending: 0
TotalTxAccepted: 0
TotalTxRejected: 0
TotalTxProcessed: 0
</td></tr>
</table>
预期的电子邮件输出:
Summary report for Risk Assessment Job on KOP-DBT0J12:
TotalTxPending: 0
TotalTxAccepted: 0
TotalTxRejected: 0
TotalTxProcessed: 0