function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
dreamrealdreamreal 

Email and Attachments code not working

What I've done is attempt to write code to attach files from the "Notes and Attachments"  list into an email that automatically sends when the opportunity stage changes to 'Send Request'. I set the target object ID to a contact to whom I wish to send the email to. I am using a template which has merge fields from opportunity. Whats currently happening is that the email is being sent to the owner of the contact, and not the contact himself. Also the attachment is not attaching, so apparently nothing is going right. Advice/criticism is much appreciated

 

 

 

trigger sendEmailAlert on Opportunity (after update) {

for(opportunity o:Trigger.new){
if(o.Stagename == 'Send Request'){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

Attachment[] queryAttachment = [select Name from Attachment where Parentid=:'accountId' order by CreatedDate DESC];

Messaging.EmailFileAttachment[] allAttachments = new Messaging.EmailFileAttachment[queryAttachment.size()];
        for(integer i=0;i<queryAttachment.size();i++)
        {
            Messaging.EmailFileAttachment fileAttachment = new Messaging.EmailFileAttachment();
            fileAttachment.setBody(queryAttachment[i].Body);
            fileAttachment.setFileName(queryAttachment[i].Name);
            allAttachments[i] =  fileAttachment;
        } 
        
        mail.setFileAttachments(allAttachments);
        mail.setTemplateID('00XQ0000000QHJS');
        mail.setTargetObjectID('003Q000000BQKyk');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


}
}
}

 

dreamrealdreamreal

Please help.

Jeremy.NottinghJeremy.Nottingh

So the easier problem first: No attachments may mean that your queryAttachment didn't return any rows. (ParentId = :'accountId' looks strange to me, shouldn't it be :o.id?) . I would put a debug statement right after that to determine what that data looks like. Then another statement in your attachment loop to make sure that it's running through that.

 

The other issue, that the email is sending to the Contact owner and not the Contact itself: I believe that you still have to specify the Contact's email address in mail.setToAddresses even if you have specified a Target Object.

 

By the way, this Trigger will not work for more than 20 records, since you have a query inside your loop. It's always a good idea to query before you start looping, to avoid the governors.

 

Jeremy