AEM Email Custom Template
AEM Email Custom Template
This blog will help us get an overall understanding of sending emails with custom templates (content, style, and attachments) with the help of the EmailService API provided by ACS Commons.
ACS Commons EmailService internally uses the OOTB MessageGateway service to send an email from the com.day.cq.mailer package. ACS Commons simplified the process in terms of sending an email through the EmailService API.
We will be covering the following topics as part of this blog:
- Sending Emails using the EmailService
- Apply CSS or style as part of the email.
- OSGI configurations are required to send emails.
- Send attachments as part of the email.
- acs-commons-email-service System Service User
As part of this blog we will be using GET servlet. Hitting servlet URL in the browser will help us to call servlet’s doGet() method which will allow us to send email having attachment.
Below are the steps that will help us implement send email functionality:
- It will require including ACS Commons as part of our POM dependency from here.
- Create the below Day CQ Mail Service OSGI configuration to declare all SMTP provider configurations that are required to send an email. As part of this blog, we are going to use Gmail as our SMTP provider, which works on 465 as a port and smtp.gmail.com as a host.
File Name: com.day.cq.mailer.DefaultMailService.xml
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
xmlns:jcr="http://www.jcp.org/jcr/1.0"
xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
jcr:primaryType="sling:OsgiConfig"
debug.email="{Boolean}true"
from.address="[email protected]"
smtp.host="smtp.gmail.com"
smtp.password="wedtyhgnuidswebm"
smtp.port="465"
smtp.ssl="{Boolean}true"
smtp.user="[email protected]"/>
Important Note: smtp.password is not an actual password we use for login. This is an app password that we can generate following the steps mentioned on the URL.
2. We can create workflows, listeners, servlets, jobs, services, etc. to trigger code for sending emails. As part of this blog, we are going to use a servlet, which will allow us to trigger emails.
Below is servlet code with reusable Java source code to send emails with the help of the EmailService API.
Reading comments at the top of every line will help us better understand code.
package com.javadoubts.core.servlets;
import com.adobe.acs.commons.email.EmailService;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.servlet.Servlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component(
service=Servlet.class,
property={
Constants.SERVICE_DESCRIPTION + "=Custom Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_GET,
"sling.servlet.paths=" + "/bin/sendemail"
}
)
public class SendEmail extends SlingAllMethodsServlet {
private static final long serialVersionUID = 1L;
@Reference
EmailService emailService;
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
protected void doGet(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws IOException {
String emailTemplatePath = "/etc/notification/email/practice/practice.html";
// Set email template dynamic variables
Map<String, String> emailParams = new HashMap<String,String>();
emailParams.put("subject","Practice AEM Send Email");
emailParams.put("message","This is practice email having attachment !!!");
// Sender Email Address
emailParams.put("senderEmailAddress","[email protected]");
// Sender Email Name
emailParams.put("senderName","Imran Khan");
// Sender Email Name
emailParams.put("recipientName","Test User");
// Array of email recipients
String[] recipients = { "[email protected]" };
String attachment1 = "This text should be in the attache txt file.";
// Create DataSource for test.txt file.
DataSource dataSource = new FileDataSource("C:/Users/imrankhan5/Desktop/test.txt");
// Create DataSource Map to attach all required set of files.
Map<String, DataSource> attachments = new HashMap<>();
attachments.put("attachment.txt", dataSource);
// sendEmail() method will return list of recipients who didn't receive email.
// sendEmail() will return an empty list if email gets successfully deliver to all recipients.
List<String> failureList = emailService.sendEmail(emailTemplatePath, emailParams, attachments, recipients);
/*
Below sendEmail overloaded method will help us to send email without attachment.
List<String> failureList = emailService.sendEmail(emailTemplatePath, emailParams, recipients);
*/
logger.error(">>>>>>>>>>> Email Sent <<<<<<<<<<<<< '{}'");
resp.setStatus(SlingHttpServletResponse.SC_OK);
resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().print("{\"response message\" : \" Email Successfully Sent !!!\"}");
}
}
3. Email Template: We can create an email template as an nt:file node with .txt and .html extensions under the /etc/notification/email hierarchy.
The main difference between .txt and .html is in applying style.
We can use .html extension with any overloaded sendEmail() method if we want to apply CSS or style as part of our email, as shown below:
emailService.sendEmail(emailTemplatePath, emailParams, recipients) method will not accept html tags in the case of .txt extension or text file, and the output will be something like what is shown below:
Create Email Template
Create an email template under the below hierarchy. /etc/notification/email/practice/practice.html
From: [email protected]
Subject: ${subject}
<div style="color: blue;">
Hello ${recipientName}
Find your message here: ${message}
From,
${senderName}
</div>
4. Hit http://localhost:4502/bin/sendemail URL in the browser to send mail as shown below:
5. Go ahead and check the sent email either in the sender’s sent box or the receiver’s inbox.
OUTPUT:
Service User
On AEM 6.2 or above, acs-commons-email-service service user is responsible to access repository.
This is an OOTB service user is configured with the expected permissions required, but additional permissions may be required if your repository design deviates from the expected structure.
ACLs: jcr:read on /etc/notification/email