Sending Emails with attachments in SAP Hybris
1. Overview
In the last article, we’ve explored how to send a basic Email in Hybris using Business process.
In this article, I will show you how to send an Email with attachments in Hybris.
Note, that this article completes the last one, I invite you to take a quick look on it before your start this one.
Unfortunately, sending Emails with attachments files in Hybris using Business Process is not supported by default, you need to customize and/or override a bunch of o classes to make it.
2. Implementation
1. First of all, create a one-to-many relation between BusinessProcessModel
and EmailAttachmentModel
.
Add this relation to your *-items.xml and run ant all
command.
<!-- ...\hybris\bin\custom\training\trainingcore\resources\trainingcore-items.xml -->
<relation code="BusinessProcess2EmailAttachmentsRel" localized="false" autocreate="true" generate="true">
<description>This relation links business process with the attachments.</description>
<sourceElement type="BusinessProcess" qualifier="process" cardinality="one" />
<targetElement type="EmailAttachment" qualifier="attachments" cardinality="many" collectiontype="list">
<modifiers partof="true" />
</targetElement>
</relation>
2. Override the DefaultEmailGenerationService
to customize the default Email generation logic.
Create a Java class called AttachmentEmailGenerationService
extends the DefaultEmailGenerationService
, and override the generate()
method.
package com.stackextend.training.core.email;
import ...;
public class AttachmentEmailGenerationService extends DefaultEmailGenerationService {
private static final Logger LOG = Logger.getLogger(AttachmentEmailGenerationService.class);
@Override
public EmailMessageModel generate(final BusinessProcessModel businessProcessModel, final EmailPageModel emailPageModel) throws RuntimeException {
// call super.generate() to fill other fields
EmailMessageModel emailMessage = super.generate(businessProcessModel, emailPageModel);
// retrieve attachments from business process and add them to the email message
List<EmailAttachmentModel> attachments = businessProcessModel.getAttachments();
emailMessage.setAttachments(attachments);
// re-save the emailMessage (Thanks Mercelo)
getModelService().saveAll(emailMessage);
// return email message
return emailMessage;
}
}
3. Register the AttachmentEmailGenerationService
as a bean in Spring, with the emailGenerationService
as an alias.
<alias alias="emailGenerationService" name="attachmentEmailGenerationService"/>
<bean id="attachmentEmailGenerationService"
class="com.stackextend.training.core.email.AttachmentEmailGenerationService"
parent="defaultEmailGenerationService">
</bean>
4. Finally, add the attachments to the Business Process and start it, to send the Email.
// Create a new instance of the process
HelloWorldProcessModel helloWorldProcessModel = (HelloWorldProcessModel) getBusinessProcessService()
.createProcess("helloWorld-" + System.currentTimeMillis(), "helloWorldEmailProcess");
// Fill the process with the appropriate data
helloWorldProcessModel.setSite(...);
helloWorldProcessModel.setCustomer(...);
helloWorldProcessModel.setLanguage(...);
helloWorldProcessModel.setCurrency(...);
helloWorldProcessModel.setStore(...);
// Add attachment to the business process
// 1. Convert your File as InputStream
DataInputStream inputStream; // new FileInputStream(myFile)
String filename; // ex: myFile.csv
String mimeType; // ex: text/csv
// 2. Create an email attachment from InputStream
EmailAttachmentModel attachment = getEmailService().createEmailAttachment(inputStream, filename, mimeType);
// 3. create new attachments list and fill it with attachment
List<EmailAttachmentModel> attachments = new ArrayList<>();
attachments.add(attachment);
// 4. set add attachments list to the business process
helloWorldProcessModel.setAttachments(attachments);
// Save the process
getModelService().save(helloWorldProcessModel);
// Then start the process = send the Email
getBusinessProcessService().startProcess(helloWorldProcessModel);
The code snippet above requires
modelService
,businessProcessService
andemailService
to be injected (Autowired).
Software Craftsmanship, Stackextend author and Full Stack developer with 6+ years of experience in Java/Kotlin, Java EE, Angular and Hybris…
I’m Passionate about Microservice architectures, Hexagonal architecture, Event Driven architecture, Event Sourcing and Domain Driven design (DDD)…
Huge fan of Clean Code school, SOLID, GRASP principles, Design Patterns, TDD and BDD.
Hello Mouad, first i want to thank for sharing these tutorials to help beginners in sap hybris. I followed the tutorials but I get this error by running the code.
missing values for [catalogVersion] in model EmailAttachmentModel () to create a new EmailAttachment
Hello,
I’m glad it helped, thanks 🙂
The reason of the error message you have here is because you don’t have a Default Catalog in your System, just navigate to HMC -> Catalog -> Catalogs -> and make the Content Catalog as the Default catalog in the system.
Good luck,
Hello Mouad,
I don’t know how to thank you. You make our life easier.
you don’t have an example about interceptors for example create our custom interceptors ?
Glad to hear that 🙂
Find here a small post about interceptors : https://www.stackextend.com/hybris/use-interceptors-in-sap-hybris/
And hou about to manipulate widget in the backoffice and adding custom widgets ?
I will try to write something about the Backoffice in the next few days.
Ok thank you very much
Hi Mouad pdf is not getting attached in email
hi Mouad, how are u ?
It worked, but I had to make a change.
in the class that inherits the DefaultEmailGenerationService.
it was necessary, save the instance of emaiLmessage
emailMessage.setAttachments(Collections.singletonList(contactUsProcessModel.getEmailAttachment())); getModelService().saveAll(emailMessage);
Yes my bad, you’re absolutely right.
Thanks Mercelo !
Hi ,
Thanks for sharing such a useful document. May I know how we can restrict jpg/jpeg attachments in the mail ?
Thanks in advance
Hi, I was adding attachment with file name having German chars, but when I received the mail, the file name is having somo other chars.. looks like decoding is not happening.
CC email address can also be added inside the generate method