WCMS Email and Process Engine Integration

The WCMS module defines the emails to be generated by the system in the same way as the WCMS pages are defined. An email created by the system contains WCMS components that are rendered within the email text. The WCMS content displayed in the emails, such as the company logo or banners, is managed through the content slots, slot names, and components and can be configured using ImpEx. The email text, such as subject line and body, are managed through Apache Velocity templates and can be configured using ImpEx or the Backoffice Administration Cockpit.

WCMS Integration

Email Page Template

The EmailPageTemplate page is an extension of the PageTemplate page type. When the system generates an email, it is based on this page template. The email page template, like the WCMS page template, can have one or more ContentSlotName objects that define the names and positions of the ContentSlot objects along with components that are allowed in the slots. The email page template can have predefined content slots with components which are available across all email pages that are associated with that template. Only the EmailPage type can be associated with the email page template.

Email Page

The EmailPage page is an extension of the AbstractPage page type. It represents formatted emails such as Customer Registration or Order Confirmation. The email page uses the masterTemplate template and defines ContentSlotName objects and any predefined content slot objects with components that are specific to that particular email. There are also two localized attributes called fromEmail and fromName and both of these attributes are used for filling in corresponding email message properties during the sending of emails. The preview function can be disabled for the EmailPage page type, as shown in the Disabling Page Preview for Email Pages section.

Renderer Template

The email subject, email body, and content of the components are generated using Velocity scripts. The RendererTemplate page contains a Velocity script, along with the Content Class name. The Velocity script contains tags which are replaced with the values from the context object provided during the rendering process.

The Velocity script that renders the email subject line is usually the simplest and may have very few Velocity tags. For example, an Order Confirmation email subject line may have a tag referring to the order number as the only component. The script that renders the email body is typically more complex and may have many Velocity tags, including tags referring to components. For example, an email body may have tags referring to the site logo, top and bottom banners, and so on. The script representing a component can have tags referring to the attributes of that component.

The Velocity tags are in the form such as ${ctx.parameterName} or ${ctx.CMSSlotContents.slotName} where ctx refers to the email Context Object passed to the renderer. More details about the context objects are provided below. The parameterName parameter can be firstName, lastName and orderNumber, for example. Also, the slotName can be siteLogo, topBanner, and bottomBanner.

Available Email Templates

The available EmailPageTemplates templates are triggered by specific events.

These templates include Subject and Body email pages that use htmlTemplate pages with the following naming schema:

  • Subject: email-<EmailPageTemplateName>Subject.vm
  • Layout and content: email-<EmailPageTemplatName>Body.vm

Both of the above templates are RendererTemplate page types, which use scripts for generating the subject and the body of an email. The available templates are located in the <HYBRIS_BIN_DIR>/base-accelerator/yacceleratorcore/resources/yacceleratorcore/import/emails directory:

The following table lists the email page templates, their descriptions, and the processes they are defined for:

Email Template Description Process
  • email-notPickedUpConsignmentCanceledBody.vm
  • email-notPickedUpConsignmentCanceledSubject.vm

Sent when a consignment has not been picked up.

Order Status

  • email-orderCancelledBody.vm
  • email-orderCancelledSubject.vm

Sent when an entire order has been canceled.

Order Status

  • email-orderCollectionReminderBody.vm
  • email-orderCollectionReminderSubject.vm

Sent to remind the customer to pick up an order in a store location.

Order Status

  • email-orderConfirmationBody.vm
  • email-orderConfirmationSubject.vm

Sent to confirm an order.

Order Status

  • email-orderMoveToCsBody.vm
  • email-orderMoveToCsSubject.vm

Sent by a cron job when a consignment has a Pickup In Store status and the shipping date is older than the threshold. By default, it is set to 120 hours.

Order Status

  • email-orderPartiallyCanceledBody.vm
  • email-orderPartiallyCanceledSubject.vm

Sent when a part of the order is canceled.

Order Status

  • email-orderPartiallyRefundedBody.vm
  • email-orderPartiallyRefundedSubject.vm

Sent when a part of the order is refunded.

Order Status

  • email-orderRefundBody.vm
  • email-orderRefundSubject.vm

Sent when the entire order is refunded.

Order Status

  • email-readyForPickupBody.vm
  • email-readyForPickupSubject.vm

Sent when an order is ready to pick up at a store location.

Order Status

  • email-deliverySentBody.vm
  • email-deliverySentSubject.vm

Sent when a delivery is sent out.

Order Status

  • email-customerRegistrationBody.vm
  • email-customerRegistrationSubject.vm

Sent when a user registers in the online storefront.

Customer Statement

  • email-forgottenPasswordBody.vm
  • email-forgottenPasswordSubject.vm

Sent when a user requests a password reset.

Customer Statement

Adding an Email Template Structure Using ImpEx

You can configure the email page templates and the email pages by ImpEx.

  1. Define the EmailPageTemplate.

    The EmailPageTemplate provides the subject, layout, and contents of the email body.

    # Email page Template
    INSERT_UPDATE EmailPageTemplate;$contentCV[unique=true];uid[unique=true];name;active;frontendTemplateName;subject(code);htmlTemplate(code);restrictedPageTypes(code)
    ;;CustomerRegistrationEmailTemplate;Customer Registration Email Template;true;customerRegistrationEmail;electronics_Email_Customer_Registration_Subject;electronics_Email_Customer_Registration_HTML;EmailPage
  2. Add a Velocity template for the EmailPageTemplate.

    The template specifies the layout for the email template.

    # Templates for WCMS Cockpit Page Edit
    UPDATE EmailPageTemplate;$contentCV[unique=true];uid[unique=true];velocityTemplate[translator=de.hybris.platform.yacceleratorcore.setup.FileLoaderValueTranslator]
    ;;CustomerRegistrationEmailTemplate;$jarResource/cmscockpit/structure-view/structure_customerRegistrationEmailTemplate.vm
  3. Define ContentSlotNames along with the permitted components for the EmailPageTemplate.

    The EmailGenerationService supports CMSParagraphComponent, CMSImageComponent, CMSLinkComponent, and CMSBannerComponent.

    INSERT_UPDATE ContentSlotName;name[unique=true];template(uid,$contentCV)[unique=true][default='CustomerRegistrationEmailTemplate'];validComponentTypes(code)
    ;SiteLogo;;CMSImageComponent,BannerComponent
    ;TopContent;;$wideContent;
    ;BottomContent;;$wideContent;
    ;Footer;;CMSLinkComponent,CMSParagraphComponent
  4. Define the RendererTemplates with the Velocity template scripts for the email subject and body.

    # Email velocity templates
    INSERT_UPDATE RendererTemplate;code[unique=true];contextClass;rendererType(code)[default='velocity']
    ;electronics_Email_Customer_Registration_HTML;de.hybris.platform.commerceservices.process.email.context.CustomerEmailContext
    ;electronics_Email_Customer_Registration_Subject;de.hybris.platform.commerceservices.process.email.context.CustomerEmailContext
    
    # Email velocity templates
    UPDATE RendererTemplate;code[unique=true];description[lang=$lang];templateScript[lang=$lang,translator=de.hybris.platform.yacceleratorcore.setup.FileLoaderValueTranslator]
    ;electronics_Email_Customer_Registration_HTML;Customer Registration HTML Email;$emailResource/email-customerRegistrationHTML_de.vm
    ;electronics_Email_Customer_Registration_Subject;Customer Registration Email Subject;$emailResource/email-customerRegistrationSubject_de.vm
  5. Add Velocity templates for the subject and body, as shown in the examples below:

    • Order confirmation email subject:
      Order Confirmation ${ctx.order.code}
    • Customer registration email body:
      <html>
      	<head>
      	</head>
      	<body bgcolor="#e4e7e8">
      	<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#e4e7e8">
      		<tr>
      			<td>&nbsp;</td>
      		</tr>
      		<tr>
      			<td align="center" valign="top">
      				<table width="610" border="6" align="center" cellpadding="0" cellspacing="0" bordercolor="#ebedee">
      					<tr>
      						<td align="center" valign="top" bgcolor="#FFFFFF">
      							<table width="570" cellpadding="0" cellspacing="0" border="0" align="center">
      								<tr>
      									<td valign="middle">
      										${ctx.cmsSlotContents.SiteLogo}
      									</td>
      								</tr>
      								<tr>
      									<td height="30" align="right" valign="middle" bgcolor="#51585c">
      										<font color="#FFFFFF" size="2" face="Arial, Helvetica, sans-serif"><a href="${ctx.secureBaseUrl}/my-account"><font color="#FFFFFF">My Account</font></a> | <a href="${ctx.baseUrl}/store-finder"><font color="#FFFFFF">Store Finder</font></a> &nbsp;&nbsp;</font>
      									</td>
      								</tr>
      								<tr>
      									<td align="center" valign="middle">
      										<a href="${ctx.baseUrl}" style="display:block; margin-top:10px;margin-bottom:10px;">${ctx.cmsSlotContents.TopContent}</a>
      									</td>
      								</tr>
      								<tr>
      									<td align="left" valign="top">
      										<p><font color="#666666" size="2" face="Arial, Helvetica, sans-serif"><b>Dear ${ctx.title} ${ctx.displayName}</b>,</font></p>
      										<p><font color="#666666" size="2" face="Arial, Helvetica, sans-serif">Thank you for registering with hybris, we hope you&rsquo;ll enjoy shopping with us.</font></p>
      										<p><font color="#666666" size="2" face="Arial, Helvetica, sans-serif">Many Thanks </font></p>
      										<p><font color="#666666" size="2" face="Arial, Helvetica, sans-serif">Customer Services</font></p>
      									</td>
      								</tr>
      								<tr>
      									<td align="center" valign="middle">
      										<a href="${ctx.baseUrl}" style="display:block; margin-top:10px;margin-bottom:10px;">${ctx.cmsSlotContents.BottomContent}</a>
      									</td>
      								</tr>
      								<tr>
      									<td height="30" align="right" valign="middle" bgcolor="#51585c">
      										<font color="#FFFFFF" size="2" face="Arial, Helvetica, sans-serif"><a href="${ctx.baseUrl}"><font color="#FFFFFF">Help</font></a> | <a href="http://www.hybris.com/hybris/en/Contact.html"><font color="#FFFFFF">Contact Us</font></a> | <a href="${ctx.baseUrl}"><font color="#FFFFFF">Terms &amp; Conditions</font></a> &nbsp;&nbsp;</font>
      									</td>
      								</tr>
      							</table>
      						</td>
      					</tr>
      				</table>
      			</td>
      		</tr>
      		<tr>
      			<td>&nbsp;</td>
      		</tr>
      	</table>
      </body>
      </html>
  6. Define the EmailPage:

    # Customer Registration Email Page
    INSERT_UPDATE EmailPage;$contentCV[unique=true];uid[unique=true];name;masterTemplate(uid,$contentCV);defaultPage;approvalStatus(code)[default='approved'];fromEmail[lang=en];fromName[lang=en]
    ;;CustomerRegistrationEmail;Customer Registration Email;CustomerRegistrationEmailTemplate;false;;from@website.com;From Website
  7. Define the components and content slots.

    # WCMS Image Components
    INSERT_UPDATE CMSImageComponent;$contentCV[unique=true];uid[unique=true];name
    ;;EmailBannerSaleNowOnImage;Email Banner Sale Now On Image
    
    # Content Slots
    INSERT_UPDATE ContentSlot;$contentCV[unique=true];uid[unique=true];name;active;cmsComponents(uid,$contentCV)
    ;;EmailTopSlot;Default Email Top Slot;true;EmailBannerSaleNowOnImage
  8. Bind reusable content slots to the EmailPageTemplate using the ContentSlotForTemplate.

    # Bind Content Slots to Email Page Templates
    INSERT_UPDATE ContentSlotForTemplate;$contentCV;uid[unique=true];position[unique=true];pageTemplate(uid,$contentCV)[unique=true]
    
    [default='CustomerRegistrationEmailTemplate'];contentSlot(uid,$contentCV)[unique=true];allowOverwrite
    ;;SiteLogo-CustomerRegistrationEmail;SiteLogo;;SiteLogoSlot;true
    ;;Footer-CustomerRegistrationEmail;Footer;;FooterSlot;true
    ;;TopContent-CustomerRegistrationEmail;TopContent;;EmailTopSlot;true
    ;;BottomContent-CustomerRegistrationEmail;BottomContent;;EmailBottomSlot;true
  9. Bind any specific content slots to the EmailPage using the ContentSlotForPage.

  10. Add common WCMS component Velocity templates. For example, for the image component:

    <img src="${ctx.parentContext.mediaBaseUrl}${ctx.media.url}" alt="${ctx.media.altText}" border="0"/>

Disabling Page Preview for Email Pages

The following example shows how to disable the preview of an email page:

# Disable preview for email pages
UPDATE CMSPageType;code[unique=true];previewDisabled
;EmailPage;true

Email Processes

Sending email is a business process containing a sequence of actions and is defined in a process definition XML file. The business process object contains the information required for the actions within the process. With email processes, the following actions are configured:

  1. Generate Email Action: The contents of the email are generated and an EmailMessage object is created. The EmailMessage objects created are attached to the business process so that the next action can act on them. This action depends on the ContextResolutionStrategy routine to impersonate the WCMS site, initialize the session context, and the EmailGenerationService routine to create the EmailMessage objects.
  2. Send Email: All the emails attached to the business process are sent using the EmailService routine. If the emails are sent successfully, the EmailMessage object is updated with the sent details.
  3. Remove Sent Email Action: If an EmailMessage object was sent successfully, it is removed from the system as shown in the following code:
<?xml version="1.0" encoding="utf-8"?>
<process xmlns="http://www.hybris.de/xsd/processdefinition" start="generateCustomerRegistrationEmail" name="customerRegistrationEmailProcess"
		processClass="de.hybris.platform.commerceservices.model.process.StoreFrontCustomerProcessModel" onError="error">

	<action id="generateCustomerRegistrationEmail" bean="generateCustomerRegistrationEmail">
		<transition name="OK" to="sendEmail"/>
		<transition name="NOK" to="error"/>
	</action>

	<action id="sendEmail" bean="sendEmail">
		<transition name="OK" to="removeSentEmail"/>
		<transition name="NOK" to="failed"/>
	</action>

	<action id="removeSentEmail" bean="removeSentEmail">
		<transition name="OK" to="success"/>
		<transition name="NOK" to="error"/>
	</action>

	<end id="error" state="ERROR">Something went wrong.</end>
	<end id="failed" state="FAILED">Could not send customer registration email.</end>
	<end id="success" state="SUCCEEDED">Sent customer registration email.</end>

</process>

Generating an Email

The first step during this process is to impersonate the site and initialize the session context with the appropriate language and currency. This is accomplished by the ContextResolutionStategy routine. Then, an email context object containing all the required values to render a Velocity script is created. This is done by the EmailContextFactory routine. Finally, an EmailMessage object is created using the EmailGenerationService routine and is attached to the business process.

DefaultContextResolutionStrategy

The DefaultContextResolutionStrategy routine resolves the customer site to be used from the business process. For instance, If the business process is a StorefrontProcess, then the customer site is retrieved from the process itself. However, if the process is an OrderProcess, then the site is retrieved from the order that is associated with that process. This strategy also tries to resolve the language and the currency to be used based on the session language and currency of the customer associated with the business process, either directly or indirectly. If the system can not resolve the language and currency to be used, then it uses the session defaults.

DefaultEmailContextFactory

The EmailContextFactory routine is responsible for creating the email context object given the EmailPage, RendererTemplate, and email business process. It retrieves the name of the email context type from the renderer template, which also contains the Velocity script referencing the email context object associated with the email template.

There are routines such as CustomerEmailContext, ForgottenPasswordContext and OrderNotificationContext in the system. All the email context objects for these routines contain general parameters such as baseUrl, secureBaseUrl, and mediaBaseUrl. The CustomerEmailContext also includes CustomerData objects such as first name, last name, and email address. The ForgottenPasswordContext also includes objects such as password token and password expiration time, along with CustomerData objects. The OrderNotificationContext includes OrderData objects such as order code, delivery address, payment information, and order entries.

The email context object also includes the content of the components of all the slots configured for email and generated using the RendererService routine. The default factory routine determines the renderer template which contains the Velocity script. For a component, simple logic is used to find a template with an ID that is the same as the component class name, prefixed with the site UID and appended with the word template. Then it creates a context object required for that component and fills it with component attribute values. Finally, with the renderer service providing the script and the context object, the system generates the content of that component. These steps are repeated for all the components of a slot and the contents of the slots are included in the main context object and mapped as "CMSContentSlots dot slotName". The components content can therefore be accessed through their contentSlotName name. For example, to access the top banner content in the Velocity script, the velocity tag is <${ctx.CMSSlotContents.topContent}> with topContent being the slotName.

The context factory adds additional parameters to the email context object based on the EmailContextVariables routine, which provide a facility to define variables based on existing parameters in the email context with a simple syntax. For example, a variable defined becomes a parameter using themeResourceUrl with a value substituting <baseUrl> and <theme> parameter values:

'ThemeResourceUrl = {baseUrl}/_ui/{theme}/'

DefaultEmailGenerationService

The EmailGenerationService routine determines the email subject and body renderer templates. Given email page templates, it generates the subject and body contents of the email using the renderer service, thus providing email context objects created by the factory described in the above section. It then creates an EmailMessage object.

Sending Emails

The SendEmailAction routine sends emails by using the EmailService routine. The action retrieves all the EmailMessages objects attached to the business process and tries to send them.

DefaultEmailService

The default email service uses Apache commons mail wrapped in MailUtils class to send EmailMessages objects and updates the object details of send status.

Deleting Emails

The RemoveEmailAction routine removes the emails from the system that are sent successfully. The action retrieves all the EmailMessages objects attached to the business process and tries to remove them from the system if they are sent successfully.

Starting the Email Process

Once an email process has been defined in an XML file and a resource bean has been created as shown below, then an email can be raised by starting the process.

<!-- Process resourcess definition -->
<bean id="customerRegistrationEmailProcessDefinitionResource" class="de.hybris.platform.processengine.definition.ProcessDefinitionResource">
<property name="resource" value="classpath:/yacceleratorcore/processes/customerRegistrationEmailProcess.xml"/>
</bean>

You can start an email process as follows:

final StoreFrontCustomerProcessModel storeFrontCustomerProcessModel = (StoreFrontCustomerProcessModel) getBusinessProcessService()
		.createProcess("customerRegistrationEmailProcess" + System.currentTimeMillis(), "customerRegistrationEmailProcess");
storeFrontCustomerProcessModel.setCMSSite(registerEvent.getCMSSite());
storeFrontCustomerProcessModel.setCustomer(registerEvent.getCustomer());
getModelService().save(storeFrontCustomerProcessModel);
getBusinessProcessService().startProcess(storeFrontCustomerProcessModel);

Audit

Data Model

Figure: Email Audit Class data model

WCMS Email Integration Data Model

Figure: Email CMS data model