Implementing DefaultMailManager

The implementation of DefaultMailManager is quite straightforward. As mentioned earlier, it uses FreeMarker to create a message body from the template and uses the Mailer API to send the message. Here is how its send() method looks:

@Component
public class DefaultMailManager implements MailManager {

private String mailFrom;
private Mailer mailer;
private Configuration configuration;

public DefaultMailManager(@Value("${app.mail-from}") String mailFrom,
Mailer mailer,
Configuration configuration) {
this.mailFrom = mailFrom;
this.mailer = mailer;
this.configuration = configuration;
}

@Override
public void send(String emailAddress, String subject, String
template, MessageVariable... variables) {
Assert.hasText(emailAddress, "Parameter `emailAddress` must not be
blank");
Assert.hasText(subject, "Parameter `subject` must not be blank");
Assert.hasText(template, "Parameter `template` must not be blank");

String messageBody = createMessageBody(template, variables);
Message message = new SimpleMessage(emailAddress, subject,
messageBody, mailFrom);
mailer.send(message);
}
...
}

As you can see, through the constructor, its dependencies are injected. Inside the test() method, it calls its createMessageBody() method to create the message body and then instantiates an instance of Message and sends it via the mailer.send() method.

Here is how the createMessageBody() method looks:

private String createMessageBody(String templateName, MessageVariable... variables) {
try {
Template template = configuration.getTemplate(templateName);
Map<String, Object> model = new HashMap<>();
if (variables != null) {
for (MessageVariable variable : variables) {
model.put(variable.getKey(), variable.getValue());
}
}
return FreeMarkerTemplateUtils.processTemplateIntoString(template,
model);
} catch (Exception e) {
log.error("Failed to create message body from template `" +
templateName + "`", e);
return null;
}
}

As you can see, inside this method, we use the instance of freemarker.template.Configuration to get a Template instance and then use FreeMarkerTemplateUtils to convert the template into a string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.206.112