Friday, 18 March 2016

How to send email with attachement in the form of pdf through Java-backed webscript

1. Register the bean in webscript-content.xml
 <bean id="webscript.com.demo.email.email-pdf-document.get" class="com.demo.webscript.email.SendMailWebscript" parent="webscript">   
             <property name="searchService" ref="searchService"/>
             <property name="contentService" ref="ContentService" />
             <property name="nodeService" ref="NodeService" />
             <property name="serviceRegistry" ref="ServiceRegistry" />
             <property name="properties" ref="global-properties" />
        </bean>

2. Create the  email-pdf-document.get.desc.xml

<webscript>
  <shortname>Download Utility</shortname>
  <description>Java Backed implementation to download document in PDF format</description>
  <url>/demo/email-pdf-document?pdfnode={pdfnode}&amp;to={to}&amp;from={from}&amp;sub={subject}&amp;mesg={feedBackMessage}&amp;attName={attachementName}</url>
  <authentication>user</authentication>
  <transaction>required</transaction>
</webscript>

3.  Create the Java class.

import demo.webscript.util.PCBConstants;

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.transform.ContentTransformer;
import org.alfresco.repo.search.impl.lucene.SolrJSONResultSet;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.cmr.repository.ContentIOException;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSetRow;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
import org.apache.log4j.Logger;
import org.springframework.extensions.webscripts.AbstractWebScript;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;

public class SendMailWebscript extends AbstractWebScript {

    private static final Logger LOG = Logger.getLogger(SendMailWebscript.class);
    private SearchService searchService;
    private NodeService nodeService;
    private ServiceRegistry serviceRegistry;
    private ContentService contentService;
    protected Properties properties;
   
    String attachName=null;

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void setSearchService(SearchService searchService) {
        this.searchService = searchService;
    }

    public void setNodeService(NodeService nodeService) {
        this.nodeService = nodeService;
    }

    public void setServiceRegistry(ServiceRegistry serviceRegistry) {
        this.serviceRegistry = serviceRegistry;
    }

    public void setContentService(ContentService contentService) {
        this.contentService = contentService;
    }

    @Override
    public void execute(WebScriptRequest req, WebScriptResponse res)
            throws IOException {

        // Email parameters:

        String toAddress = req.getParameter("to");
        String fromAddress = req.getParameter("from");
        String message = req.getParameter("mesg");
        String subject = req.getParameter("sub");
        String nodeID = req.getParameter("pdfnode");
       

        String node = "workspace://SpacesStore/" + nodeID;

        NodeRef attachNodeRef = new NodeRef(node);
        LOG.debug("node id is ? " + attachNodeRef);
        if (!nodeService.exists(attachNodeRef)) {
            throw new AlfrescoRuntimeException("Sorry, " + attachNodeRef
                    + " doesn't exist");
        }

        String pcbfilename = (String) nodeService.getProperty(attachNodeRef,
                PCBConstants.PROPERTY_PCBFILENAME);
         
       
        LOG.debug("pcbfilename is  ? " + pcbfilename);

        if (attachNodeRef != null && pcbfilename != null) {

            ContentData contentData = (ContentData) nodeService.getProperty(
                    attachNodeRef, ContentModel.PROP_CONTENT);

            LOG.debug("Mine Type" + contentData.getMimetype());

            LOG.debug("email is In Progress with attachement: " + pcbfilename
                    + " Message is: " + message.replace("AND", "&"));
            sendEmailToUser(toAddress, fromAddress, attachNodeRef, subject,
                    message.replace("AND", "&"), pcbfilename);

        } else {

            LOG.debug("email is In Progress without attachement: " + pcbfilename
                    + " Message is: " + message.replace("AND", "&") + "");
            sendEmailToUser(toAddress, fromAddress, null, subject,
                    message.replace("AND", "&"), pcbfilename);

        }

    }

    public void sendEmailToUser(String toAddress, String fromAddress,
            NodeRef attachNodeRef, String Subject, String mesg,
            String pcbfilename) {

        LOG.debug("Inside sendEmailToUser with subject : " + Subject
                + " Message is : " + mesg);

        try {
            // Email logic

            Properties props = new Properties();

            props.put("mail.smtp.host", properties.getProperty("mail.host"));
            props.put("mail.smtp.port", properties.getProperty("mail.port"));

            Session session = Session.getInstance(props);

            // Create a default MimeMessage object.
            MimeMessage msg = new MimeMessage(session);

            msg.setFrom(new InternetAddress(fromAddress));

            LOG.debug("Multiple Recipent is " + toAddress);

            // Set To: header field of the header.
            for (String to : toAddress.split(",")) {
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                        to));
            }

            String sub = ("From Keenan's P&C Bridge: " + Subject);

            msg.setSubject(sub);

            String message = ("<div style=\"white-space: nowrap;\">" + mesg);

            // msg.setContent(message,"text/html;charset=utf-8");

            msg.setSentDate(new Date());

            // Create the message part
            BodyPart messageBodyPart = new MimeBodyPart();

            // Fill the message
            messageBodyPart.setContent(message, "text/html;charset=utf-8");

            MimeMultipart mail = new MimeMultipart("mixed");
            mail.addBodyPart(messageBodyPart);

            if (attachNodeRef != null) {
                // Part two is attachment
                ContentData contentData = (ContentData) nodeService.getProperty(
                        attachNodeRef, ContentModel.PROP_CONTENT);
                LOG.debug("Mine Type" + contentData.getMimetype());

                if(!contentData.getMimetype().equalsIgnoreCase("application/pdf")){
                      LOG.debug("attachement is not PDF");
                      String fileName = (String) nodeService.getProperty(attachNodeRef,
                                ContentModel.PROP_NAME);
                      attachName = fileName;
                      addAttachement(attachNodeRef, mail, true);
                }else{
                      LOG.debug("attachement is PDF");
                      attachName= pcbfilename;     
                    addAttachement(attachNodeRef, mail, false);
                }
                LOG.debug("attachement is successful");
            }

            // Send the complete message parts
            msg.setContent(mail);

            // Send message
            Transport.send(msg);
            LOG.debug("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }

    }

    public void addAttachement(NodeRef nodeRef, MimeMultipart content,
            Boolean convert) throws MessagingException {
        LOG.debug("Inside Add Attachement");
        byte array[] = new byte[0];
        ContentReader reader = serviceRegistry.getContentService().getReader(
                nodeRef, ContentModel.PROP_CONTENT);
//        String fileName = (String) nodeService.getProperty(nodeRef,
//                ContentModel.PROP_NAME);
//        String filename = attachName;
        String type = reader.getMimetype().split("/")[0];
        if (!type.equalsIgnoreCase("image")
                && !reader.getMimetype().equalsIgnoreCase("application/pdf")
                && convert.booleanValue()) {
            ContentWriter writer = contentService.getTempWriter();
            writer.setMimetype("application/pdf");
            String srcMimeType = reader.getMimetype();
            ContentTransformer transformer = contentService.getTransformer(
                    srcMimeType, "application/pdf");
            if (transformer != null) {
                try {
                    transformer.transform(reader, writer);
                    reader = writer.getReader();
                    attachName = attachName.substring(0, attachName.lastIndexOf('.'));
                    attachName = (new StringBuilder()).append(attachName)
                            .append(".pdf").toString();
                } catch (ContentIOException ex) {
                    LOG.warn("could not transform content");
                    LOG.warn(ex);
                    reader = serviceRegistry.getContentService().getReader(
                            nodeRef, ContentModel.PROP_CONTENT);
                }
            }
        }
        try {
            MappedByteBuffer buf = reader.getFileChannel().map(
                    java.nio.channels.FileChannel.MapMode.READ_ONLY, 0L,
                    reader.getSize());
            if (reader.getSize() <= 0x7fffffffL) {
                array = new byte[(int) reader.getSize()];
                buf.get(array);
            }
        } catch (IOException ex) {
            LOG.error("There was an error reading file into memory.");
            LOG.error(ex);
            array = new byte[0];
        }

        LOG.debug("Pre-state of attachment");

        ByteArrayDataSource ds = new ByteArrayDataSource(array,
                reader.getMimetype());
        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setFileName(attachName);
        attachment.setDataHandler(new DataHandler(ds));
        content.addBodyPart(attachment);
    }

    public NodeRef checknodeRefByString(String nodeName) {

        NodeRef nodeRef = null;
        LOG.debug("Node to be searched is :" + nodeName);
        SearchParameters params = new SearchParameters();
        params.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
        params.setLanguage(SearchService.LANGUAGE_SOLR_FTS_ALFRESCO);
        params.setQuery("PATH:\"/app:company_home/cm:Keenan/cm:PCB/cm:CMS/cm:Webconversion//*\" AND TYPE:\"pcbcms:pcbcmsDocument\" AND @name:"
                + nodeName + "");
        SolrJSONResultSet results = (SolrJSONResultSet) searchService
                .query(params);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Query result length: " + results.length());
        }

        for (ResultSetRow row : results) {
            nodeRef = row.getNodeRef();
            if (LOG.isDebugEnabled()) {
                LOG.debug("List for query response : " + nodeRef);
            }
            break;
        }

        return nodeRef;
    }

}

No comments:

Post a Comment