Day 2 : Email Configuration in Hybris
There are many ways to configure email functionality in Hybris. I have worked in projects where the entire email functionality was handled by third party systems and then there were projects where it was managed in Hybris itself.
When it comes to email configuration in hybris itself, we can manage it through asynchronous approach using listener class or through direct service classes. In my current project we are handling it synchronously with the help of email templates.
Our current use case requires us to send emails for particular products when workflow moves from one state to other. These are all internal emails. So only basic information is required.
- First we need to have the email context defined with all the getters and setters. In our case, this is a simple WorkflowEmailContext which extends VelocityContext. There is no particular logic written in this class. The context class will hold the data for the renderer template.
- Define velocity template for the email content. It can be as simple as a normal static html message. Dynamic data can be populated from the EmailContext class.
- Associate the velocity template with the context class.
INSERT_UPDATE RendererTemplate; code[unique = true] ; description[lang = en] ; templateScript[lang = en, translator = de.hybris.platform.commerceservices.impex.impl.FileLoaderValueTranslator]; rendererType(itemtype(code), code); contextClass
; workflowReworkPartEmailTemplate ; Template for Workflow Part Email ; jar:com.sap.core.setup.TestcoreSystemSetup&/testcore/mail/test_work_email_en.vm ; RendererTypeEnum:velocity ; com.sap.test.core.service.mail.context.WorkflowEmailContext
4. Define an email service class and use the below code snippet
final RendererTemplateModel template = rendererService.getRendererTemplateForCode(templateCode);
final HtmlEmail htmlEmail;
try {
htmlEmail = (HtmlEmail) MailUtils.getPreConfiguredEmail();
// Add To Email
htmlEmail.addTo(toemail);
// Add CC Email
htmlEmail.addCc(email);
htmlEmail.setFrom(fromEmail);
htmlEmail.setSubject(subject);
htmlEmail.attach(attachment);
//Create a writer where the rendered text will be written to
final StringWriter mailMessage = new StringWriter();
//Render the template using the context object
rendererService.render(template, ctx, mailMessage);
//set rendered text to mail and send it
htmlEmail.setHtmlMsg(mailMessage.toString());
htmlEmail.send();
} catch (final EmailException e) {
LOG.error("Error in Getting preconfigured email " + e.getMessage(), e);
}
5. Last but not the least, configure your smtp server in local.properties.
mail.smtp.server=mailhub.test.com
mail.smtp.port=25
mail.smtp.user=
mail.smtp.password=
I hope this has been helpful. I would like to hear about how you do it in your projects as well.