Implementing AsyncMailer

AsyncMailer, as its name suggests, sends a message asynchronously. And, as shown in the UML diagram in Figure 10.17, it relies on JavaMailSender to actually send messages. Its implementation looks like the following: 

@Component
public class AsyncMailer implements Mailer {
...
@Async
@Override
public void send(Message message) {
Assert.notNull(message, "Parameter `message` must not be null");

try {
SimpleMailMessage mailMessage = new SimpleMailMessage();

if (StringUtils.isNotBlank(message.getFrom())) {
mailMessage.setFrom(message.getFrom());
}
if (StringUtils.isNotBlank(message.getSubject())) {
mailMessage.setSubject(message.getSubject());
}
if (StringUtils.isNotEmpty(message.getBody())) {
mailMessage.setText(message.getBody());
}
if (message.getTo() != null) {
mailMessage.setTo(message.getTo());
}

mailSender.send(mailMessage);
} catch (MailException e) {
log.error("Failed to send mail message", e);
}
}
}

As you can see, we use the @Async annotation to tell Spring that this send(Message) method should be invoked asynchronously. Inside the method, we create an instance of org.springframework.mail.SimpleMailMessage and then pass it to Spring's JavaMailSender. Underneath, JavaMailSender depends on the JavaMail APIs to send out messages.

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

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