Saturday 28 March 2015

Newsletters-Email Campaigns in AEM6/CQ5


Email Marketing is one of the important aspect which enable the organizations to interact with their audience frequently for latest update, news etc. There are lot of Email Marketing softwares are available in the market. AEM also ships with the such functionality where AEM can send the the emails such as newsletters to list of users that exists in JCR.


Use-Case : Send the NewsLetters to the Subscribed Customers.


Here are the steps : 

1) First configure the Day CQ Mail Service via OSGi configuration.
2) Create Brand ---> Create Campaign(under brand) ----> Create Newsletter(under Campaign)


3) Create a Lead through Campaign Console, just mention the Mail and save.


4) Open the Newsletter and change the settings, Just fill From Name, From Address, Subject for now & OK.



5) Now to test the newsletter and to check whether email service properly configured or not. Press Ctrl+Alt+C and select the profile (the lead you created in step 3). Reload the Page.

6) Click on the Test button display on the editbar of newsletter.

7) A dialog will open, where you can add the recipient address and test. If successful, you will get the message as below.


 In case if issue comes then try to publish/replicate your newsletter and lead, also look for the mail configuration.

8) Newsletters are mean to send the list of users subscribed, So create a List from Campaign Console of AEM. This List is same as group in repository.

9) Click on the settings from step 6. And in bottom of dialog add the List (Default Recipient List) that you created in step 8. Ty to keep List name should name meaningful such as newsletters-xxxxxx.


10) Now create a custom component say : Subscribe me. This component will add the subscribed user under the group/list you created. Below snippet of code of jsp :


 <%@include file="../../../global.jsp" %>  
 <%@page session="false" %>  
 <div id="response">  
   <pre style="color: #ff0000"></pre>  
 </div>  
 <form id="subscribe">  
   <input type="text" name="subscribe_email"/></br></br>  
   <button type="submit">Subscribe Now</button>  
 </form>  
 <script>  
   (function ($) {  
     function processForm(e) {  
       $.ajax({  
         url: '/bin/subscriber',  
         dataType: 'text',  
         type: 'post',  
         data: $(this).serialize(),  
         success: function (data) {  
           console.log(data);  
           $('#response pre').html(data);  
         },  
         error: function (jqXhr, textStatus, errorThrown) {  
           console.log(errorThrown);  
         }  
       });  
       e.preventDefault();  
     }  
     $('#subscribe').submit(processForm);  
   })(jQuery);  
 </script>  

11) Create servlet to handle the request for subsciber :


 package com.aem.servlets;  
 import org.apache.commons.lang.RandomStringUtils;  
 import org.apache.felix.scr.annotations.Component;  
 import org.apache.felix.scr.annotations.Properties;  
 import org.apache.felix.scr.annotations.Property;  
 import org.apache.felix.scr.annotations.Service;  
 import org.apache.jackrabbit.api.security.user.Authorizable;  
 import org.apache.jackrabbit.api.security.user.Group;  
 import org.apache.jackrabbit.api.security.user.User;  
 import org.apache.jackrabbit.api.security.user.UserManager;  
 import org.apache.sling.api.SlingHttpServletRequest;  
 import org.apache.sling.api.SlingHttpServletResponse;  
 import org.apache.sling.api.resource.Resource;  
 import org.apache.sling.api.resource.ResourceResolver;  
 import org.apache.sling.api.servlets.SlingAllMethodsServlet;  
 import org.slf4j.Logger;  
 import org.slf4j.LoggerFactory;  
 import javax.jcr.Session;  
 import javax.jcr.ValueFactory;  
 import java.util.Iterator;  
 import java.util.Map;  
 @Component(immediate = true, metatype = false, label = "Create Subscriber")  
 @Service  
 @Properties(value = {  
     @Property(name = "sling.servlet.methods", value = "POST"),  
     @Property(name = "sling.servlet.paths", value = "/bin/subscriber")  
 })  
 public class GenerateSubscriberServlet extends SlingAllMethodsServlet {  
   private static final Logger logger = LoggerFactory.getLogger(GenerateSubscriberServlet.class);  
   @Override  
   protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {  
     ResourceResolver resourceResolver = request.getResourceResolver();  
     boolean flag = true;  
     String msgToPrint = "";  
     try {  
       Map<String, String> parameterMap = request.getParameterMap();  
       String email_id = "";  
       if (parameterMap.containsKey("subscribe_email") && resourceResolver != null) {  
         email_id = request.getParameter("subscribe_email");  
         UserManager userManager = resourceResolver.adaptTo(UserManager.class);  
         if (userManager != null) {  
 // Change Group Name as you given in step 9.  
           Group group = resourceResolver.resolve("/home/groups/n/newsletters").adaptTo(Group.class);  
           Iterator<Authorizable> authorizableIterator = group.getMembers();  
           while (authorizableIterator.hasNext()) {  
             if (authorizableIterator.next().getPrincipal().getName().equals(email_id)) {  
               msgToPrint = "User already Registered";  
               flag = false;  
               break;  
             }  
           }  
           if (flag) {  
             Session session = resourceResolver.adaptTo(Session.class);  
             ValueFactory valueFactory = session.getValueFactory();  
             User subscriberUser = userManager.createUser(email_id, RandomStringUtils.randomAlphanumeric(20).toUpperCase());  
             subscriberUser.setProperty("cq:authorizableCategory", valueFactory.createValue("mcm"));  
             subscriberUser.setProperty("profile/email", valueFactory.createValue(email_id));  
             group.addMember(subscriberUser);  
             session.save();  
             if (subscriberUser != null) {  
               msgToPrint = "User Registered Successfully";  
             }  
           }  
         }  
       }  
       response.getWriter().write(msgToPrint);  
     } catch (Exception ex) {  
       logger.error(ex.getMessage());  
     }  
   }  
 }  

12) Now build the codebase, Drop the component "Subscribe Me" from Side-Kick and subscribe the user as below :


 You will notify that you are registered. In case existing subscribed user come to re-register again, it will prompt :
Email Validation not so far done in this code, So Enter the valid email address.
13) You can view the member of List/Group created in step 9 via Campaign console & then List (in servlet i have hard-coaded the group name, you can use the OSGi configuration for that also).


 14) Now final steps are to send the email, Open the newsletter created.
15) Click on the send button, list of users populate as per the group/list. Complete the wizard.


 16) You will have newsletter in your Inbox.


Thanks !!!

1 comment:

  1. Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you.
    digitala nyhetsbrev

    ReplyDelete