Notes and Attachment Trigger

 trigger attachmentFileTrigger on Attachment (after insert) {

    if(Trigger.isInsert && Trigger.isAfter){

        List<Contract> contracts = [SELECT Id,Name, Owner.Email, (Select parentId FROM Attachments WHERE Id IN :Trigger.newMap.keySet()) FROM Contract];

        List<Attachment> files = [SELECT Name, Body,parentId, ContentType FROM Attachment WHERE Id IN :Trigger.newMap.keySet()];

        System.debug('List of Contracts : '+ contracts);

        Set<Id> setOfIds = new Set<Id>();

        for(Attachment fl : files){

            if(fl.parentId != Null){

                setOfIds.add(fl.parentId);

            }

        }

        System.debug('setOfIds : '+ setOfIds);

        if(!setOfIds.isEmpty()){

            for(Contract c : [SELECT Id,Name, Owner.Email From Contract where id IN : setOfIds]){

                System.debug('##1');

                List<Messaging.EmailFileAttachment> attachments = new List<Messaging.EmailFileAttachment>();

                for(Attachment a : files){

                    if(a.Body != null){

                        System.debug('##2');

                        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();

                        attachment.setFileName(a.Name);

                        attachment.setBody(a.Body);

                        attachments.add(attachment);

                    }

                }

                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

                List<string> toEmails = new List<String>();

                List<string> ccEmails = new List<String>();

                toEmails.add('ashutoshvijay892@gmail.com');

                ccEmails.add('ravijangid16aug@gmail.com');

                email.setToAddresses(toEmails);

                email.setCcAddresses(ccEmails);

                email.setWhatId(c.Id);

                String body = '<!DOCTYPE html><html><head></head><body><p>Hello Dear, </p>'+'<p>This Trigger is on Attachment Object and if parentId is match to Contract Object than send email with file from Email Template.</p></br>'+'<p>Regards,<br/> Ravi Jangid </p></body></html>';

                email.setHtmlBody(body);

                //email.setTemplateId('Classic Email Template API Name');

                email.setSubject('New file uploaded for Contract');

                email.setFileAttachments(attachments);

                Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});

                System.debug('email : '+ email);

                System.debug('attachments : '+ attachments);

            }

        }

    }

}

Comments

Popular posts from this blog

Custom List View Button In Salesforce

Get Record Id RecordId in LWC

PDF LWC (Link for pdf liabrary)