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
sam_Adminsam_Admin 

Error when using template id in trigger to send email

I want to send an email to the owner  when someone attach a file to opp, so here is my trigger it works fine i just use plain text body and html body but i want to insert template so i created template and used that id by trigger doesn't shows up any error but when i try to attach file to opp record it throws me error saying Invalid Id: john@company.com, here is my trigger

 


Trigger AttachmentEmail on Attachment (after insert) {
 set<Id> aId = new set<id>();
 for(Attachment a:trigger.new){
   aId.add(a.Id);    
 }
 
 list<Attachment>alist=[select Id, Name, ParentId, OwnerId from Attachment  where Id in: aId];
 String parentObj = alist[0].parentId;
 if(parentObj.startsWith('006')){
 
     list<User> ulist = [select Id, email from User where Id =:alist[0].OwnerId];
     String emailId = ulist[0].email;
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        //String[] toAddresses = new String[] {emailId};
                        mail.setTargetObjectId(emailid);
                        mail.setTemplateId('00XQ0000000MIJJ');
                        //mail.setToAddresses(toAddresses);             
                       // mail.setSubject('A new file is attached to your request' );
                       // mail.setBccSender(false);
                       // mail.setUseSignature(false);
                        //mail.setPlainTextBody('Please click on the link below to view your file');
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
            }

}

 

 

Marty Y. ChangMarty Y. Chang

Hello, sam_Admin,

 

The setTargetObjectId method expects the Salesforce "ID of the contact, lead, or user to which the email will be sent", as documented in the Force.com Apex Code Developer's Guide.

 

I think your code will work if you just make the following change:

 

// Original code:
// String emailId = ulist[0].email;
String emailId = ulist[0].Id;