How to send attachments in email CQ5/AEM

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

Basically, you need to have instance of 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);  
                List<String> namesList = new ArrayList<String>();  
                Iterator<Resource> fields = FormsHelper.getFormElements(request.getResource());  
                while (fields.hasNext()) {  
                     Resource field = (Resource);  
                     FieldDescription[] descs = FieldHelper.getFieldDescriptions(request, field);  
                     for (FieldDescription desc : descs)  
                          if (!desc.isPrivate()) {  
                List<RequestParameter> attachments = new ArrayList<RequestParameter>();  
                for (String name : namesList) {  
                     RequestParameter rp = request.getRequestParameter(name);  
                     if (null!=rp && !rp.isFormField() &&rp.getSize() > 0L) {  
                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.setMsg(getEmailBody(//get body);  
                for (String rec : mailTo) {  
                email.setSubject(//set subject);  
                email.setFrom(//set from);  
           catch (EmailException e) {  
                throw new ServletException("Form can't be posted",e);  

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s