Send email and attach files/images from AEM

28 / May / 2015 by Manisha Bano 6 comments

To Send email from AEM , follow the steps written below:

Gmail SMTP Server could also be used to relay messages from your device or application. If you connect using SMTP, you can only send mail to Gmail or Google Apps users; if you connect using SSL/TLS, you can send mail to anyone.

If your device or application supports SSL – connect to smtp.gmail.com on port 465.

To connect with SSL, you need to provide a Google username and password for authentication.

You can connect it in this way:

  • CONFIGURE MAIL SERVER

Go to the felix configuration by hitting the url – http://localhost:4502/system/console/configMgr then open the Day CQ Mail Service and configure like this

Screenshot from 2015-04-14 11:11:12

  • ADD A TEMPLATE

A template is basically created in /etc/notification. The MailTemplate class provides email text templating functionality. Templates are nt:file nodes in the repository representing a text file (or html will also work, as in this case).

The template will create a structure of how your email will look like. The ${subject} and ${message} act as the replacement variables.

And then write the code as follows:

Screenshot from 2015-04-14 12:06:02

  • CREATE A SERVLET

Create a servlet and write the following code snippet :

@Reference
MessageGatewayService messageGatewayService;

This will get all the values with request as parameters in form of map.

@SuppressWarnings("unchecked")
parameterNames = request.getParameterNames();
parameters = new HashMap<String, String>();
while (parameterNames.hasMoreElements()) {
final String key = parameterNames.nextElement();
parameters.put(key, request.getParameter(key));
}

MailTemplate will create a mail template

Resource templateRsrc = request.getResourceResolver().getResource("/etc/notification/send-email.html");
String mailId = request.getParameter("mailId");
  • ATTACH IMAGES

Email attachments can send any file attached with the mail

 

EmailAttachment attachment = new EmailAttachment();
attachment.setPath("<image-Path>");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Any Description");
attachment.setName("Any name you can set");
final MailTemplate mailTemplate = MailTemplate.create(templateRsrc.getPath(), templateRsrc.getResourceResolver().adaptTo(Session.class));
final HtmlEmail email = mailTemplate.getEmail(StrLookup.mapLookup(properties), HtmlEmail.class);
email.addTo(mailId);

The getEmail method returns the choosen (type argument) email implementation, as long as the type extends Email and has a publically accessible default constructor. Out of the box the three email implementations provided by the Apache Commons Email library can be used: SimpleEmail, HtmlEmail and MultiPartEmail.

messageGateway = messageGatewayService.getGateway(HtmlEmail.class);
messageGateway.send(email);

MessageGateway is an Object capable of sending a message to a recipient. This is an ServiceProvider to be used as to register as an OSGI service. Gateways can be accessed via MessageGatewayService.

  • ATTACH IMAGES FROM DAM

To attach any image from dam you can fetch the image in binary format and send it to desired recipient in this way,

Resource imageNodeRes = request.getResourceResolver().getResource("/content/dam/indeximg/anil-gupta-nav-img.jpg/jcr:content/renditions/original");
Node imageNode=imageNodeRes.adaptTo(Node.class);
Node contentNode = imageNode.getNode("jcr:content");
Binary imageBinary = contentNode.getProperty("jcr:data").getBinary();
InputStream imageStream = imageBinary.getStream();
ByteArrayDataSource imageDS = new ByteArrayDataSource(imageStream,"image/png");
email.attach(imageDS,"Some Image","Some Description");
  • EXPLICITLY EMBEDD IMAGES

Images can be Embbed explicitly by this way but this will violate the mail Template and send mail in its own way.

URL url = new URL("<Any URL>");
String cid = email.embed(url, "<Any Name>");
email.setHtmlMsg("<html><body><img src=\"cid:"+cid+"\"></body></html>");

Thank you..

Have nice time :)

Tag -

FOUND THIS USEFUL? SHARE IT

comments (6)

  1. Damon

    Hi, awesome info, question, can I preview an email in the browser (fully rendered) without sending it?

    Reply
  2. Pradeep

    Hey, i am getting this error while using attach method in email – The method attach(EmailAttachment, String, String) is undefined for the type Email.
    I have added all the imports correctly.

    Reply
  3. Neha

    I am getting this exception in CQ while trying to send an email:
    javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed;

    Reply
  4. Purnendra

    where are we adding attachment with email ? I am still not sure how are we adding Attachment with email object??

    Reply
    1. Manisha Bano Post author

      you can attach any file using attach method as ::
      InputStream ImageStream; // file as inputStream
      String Type ; // mime:type of file
      ByteArrayDataSource fileDS = new ByteArrayDataSource(imageStream, type);
      email.attach(FileDS,”img name” ,”file Description” );

      Then you can send..

      Reply

Leave a comment -