发送电子邮件时将参数显示在FreeMarker模板中

时间:2017-06-14 03:04:05

标签: java spring spring-boot smtp freemarker

通过使用Spring Boot,我成功发送了电子邮件,但我无法将参数传递到模板ftl

MailService.java

@Service
public class MailService {

    @Autowired
    private EmailService emailService;

    public void sendEmailWithTemplating(String userEmail, String username) throws UnsupportedEncodingException, CannotSendEmailException {
        InlinePicture inlinePicture = createGalaxyInlinePicture();

        final Email email = DefaultEmail.builder()
                    .from(new InternetAddress("xxx@gmail.com",
                            "Smart Reservation System"))
                    .to(newArrayList(
                            new InternetAddress(userEmail,
                                    username)))
                    .subject("registration of a new user")
                    .body("")
                    .encoding("UTF-8").build();

        String template = "emailTemplate.ftl";

        Map<String, Object> modelObject = ImmutableMap.of(
                    "title", "Emperor",
                    "name", "Cleon I"
            );

        emailService.send(email, template, modelObject, inlinePicture);
    }

    private InlinePicture createGalaxyInlinePicture() {
        ClassLoader classLoader = getClass().getClassLoader();
        File pictureFile = new File(
                     classLoader.getResource(
                         "images/parcking.jpg")
                     .getFile());
        Preconditions.checkState(pictureFile.exists(), 
                     "There is not picture %s", pictureFile.getName());

        return DefaultInlinePicture.builder()
                    .file(pictureFile)
                    .imageType(ImageType.JPG)
                    .templateName("parcking.jpg").build();
    }

}

例如我想在我的模板sendEmailWithTemplating()中显示emailTemplate.ftl方法参数的用户名参数

我发现我们可以使用像

这样的地图
    Map<String, Object> modelObject = ImmutableMap.of(
                "username", username,
                "useremail", userEmail
        );

然后显示如下参数:

emailTemplate.ftl

<!doctype html>
<html>
<body>
    <p>
        Dear<em>{{username}}</em>,//but it display it like {{username}} it coundn't display the value of username
    </p>
    <p>
        <strong>Congratulations!</strong> You’re Now Signed Up.
    </p>
    <p style="align: center">
        <img src="parcking.jpg" />
    </p>

    <p>
         --<br /> Regards<br />
         <em>SRS Team</em><br />
    </p>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

FreeMarker的语法是${username}