When i was asked to write this, i created a mail service and the method was something like this. Please see this is just a reference code.
The messageGateway service can be fetched using
/** The message gateway service. */
@Reference(cardinality=ReferenceCardinality.MANDATORY_UNARY)
private MessageGatewayService messageGatewayService;
We do some dynamic token replacement for which we use MessageFormater or StringFormatter classes.
You can also use StrLookup.mapLookup (This is an apache commons-lang file) and you can pass in any <String, String> map and this will do any dynamic replacement for you.
public void sendBulkEmail(String[] users, String templatePath, String[] mailTokens, String emailFrom, String emailSubject) {
if (null != users && users.length > 0) {
ResourceResolver adminResolver = null;
try {
adminResolver = getResourceResolverFactoryReference().getAdministrativeResourceResolver(null);
Resource templateRsrc = adminResolver.getResource(templatePath);
if (null != templateRsrc) {
ArrayList < InternetAddress > emailRecipients = new ArrayList < InternetAddress > ();
for (String user: users) {
emailRecipients.add(new InternetAddress(user));
}
Node templateNode = templateRsrc.adaptTo(Node.class);
HtmlEmail email = new HtmlEmail();
email.setTo(emailRecipients);
email.setSubject(emailSubject);
email.setFrom(emailFrom);
//This will do the token replacement for dynamic elements.
for (String token: mailTokens) {
email.setHtmlMsg(MessageFormat.format(templateNode.getProperty(Constants.XYZ).getString(), token));
}
MessageGateway < HtmlEmail > messageGateway = this.messageGatewayService.getGateway(HtmlEmail.class);
log.debug("gateway service is and gateway is {}", messageGatewayService);
if (null != messageGateway) {
messageGateway.send(email);
}
}
} catch (Exception e) {
log.error("Exception in sending bulk email {}", e.getMessage());
} finally {
if (null != adminResolver && adminResolver.isLive()) {
adminResolver.close();
}
}
}
}
This is enough to send any emails. You can use this mail service code to send a single email by customizing the code in some places
No comments:
Post a Comment
If you have any doubts or questions, please let us know.