+ Start a Discussion
Narsimha RaoNarsimha Rao 

Error when sending emails using Lightning Email Template with attachments through Apex code

Hello,
I am facing an error "invalid cross reference object" when sending Salesforce Files as attachments via Lightning Email Template through apex code.
I have created a Lightning email template and attached an attachment to that. When we send this email template through apex, it throws the below error. If the attachment is removed from the template, it works fine.

Error message:
System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

Apex code:
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
semail.setTemplateId('00X7F000001THAPUA4');
semail.setTargetobjectid('0037F00001FBiQqQAL');
semail.setWhatId('0017F00001LRyRVQA1');
semail.setSaveAsActivity(false);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});

Content Deliveries and Public Links is checked in my org. Any help would be appreciated.

Thanks!!