简体   繁体   中英

Display arguments into a FreeMarker template when send email

By using Spring Boot, I sent email successful, but I can't pass arguments into template 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();
    }

}

for example I want to display username argument which is argument of sendEmailWithTemplating() method into my template emailTemplate.ftl

I found that we could use a Map like

    Map<String, Object> modelObject = ImmutableMap.of(
                "username", username,
                "useremail", userEmail
        );

And then display arguments like :

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>

FreeMarker的语法是${username}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM