April 3, 2020
Estimated Post Reading Time ~

How to send attachments in email CQ5/AEM

There are often requirements for sending attachments in emails. I was using the upload OOTB form component and I had slightly customized the OOTB form component but whenever I was sending an email on my local dev machine I was not receiving the attachments in email.

Basically, you need to have an instance of the multipart email (apache commons library) and once you have that, it is easy enough to send that email.

The below code sample is what I used to send the attachment in the email.

Please see that this is not production-ready and not complete code. You may have to place some pieces here and there.


 try {
  List < String > contentNamesList = new ArrayList < String > ();
  Iterator < String > names = FormsHelper.getContentRequestParameterNames(request);
  while (names.hasNext()) {
   String name = (String) names.next();
   contentNamesList.add(name);
  }
  Collections.sort(contentNamesList);
  List < String > namesList = new ArrayList < String > ();
  Iterator < Resource > fields = FormsHelper.getFormElements(request.getResource());
  while (fields.hasNext()) {
   Resource field = (Resource) fields.next();
   FieldDescription[] descs = FieldHelper.getFieldDescriptions(request, field);
   for (FieldDescription desc: descs) {
    contentNamesList.remove(desc.getName());
    if (!desc.isPrivate()) {
     namesList.add(desc.getName());
    }
   }
  }
  namesList.addAll(contentNamesList);
  List < RequestParameter > attachments = new ArrayList < RequestParameter > ();
  for (String name: namesList) {
   RequestParameter rp = request.getRequestParameter(name);
   if (null != rp && !rp.isFormField() && rp.getSize() > 0 L) {
    attachments.add(rp);
   }
  }
  MultiPartEmail mpEmail;
  Email email;
  if (attachments.size() > 0) {
   mpEmail = new HtmlEmail();
   email = mpEmail;
   for (RequestParameter rp: attachments) {
    ByteArrayDataSource ea = new ByteArrayDataSource(rp.getInputStream(), rp.getContentType());
    mpEmail.attach(ea, rp.getFileName(), rp.getFileName());
   }
  } else {
   email = new HtmlEmail();
  }
  email.setCharset("utf-8");
  email.setMsg(getEmailBody( //get body);  
     for (String rec: mailTo) {
      email.addTo(rec);
     }
     email.setSubject( //set subject);  
      email.setFrom( //set from);  
       getMessageGatewayService().getGateway(Email.class).send(email);
      }
      catch (EmailException e) {
       throw new ServletException("Form can't be posted", e);
      }



By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.