[SalesForce] How to send an email before delete record using Email Template

I would like to send an email by using email template before delete a specific record.
I'm using a before delete trigger and I receive the email, the problem is that the email is almost empty, without any record details.
The same email template is used for after update and it works fine (record details are correctly sent).
Any suggestions?

trigger opportunityNotificheOAS on Opportunity (before delete, after update) {
    if(Trigger.isDelete){ 
        for(Opportunity o : Trigger.old){ 
            emails.add(prepareEmail(o)); 
        } 
    } 

In the prepareEmail method I do the following:

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId(et.id); mail.setTargetObjectId(c.Id); mail.setWhatId(o.Id);

Best Answer

I think the problem is that the email generation and sending takes place in a separate after your code has run, and by that time the record you're interested in doesn't exist.

I would have a delete flag on the object which when checked means an email is sent (via an update trigger) and then use a time-baed workflow or a scheduled batch apex job to do clean up afterwards, removing all records where that checkbox is true.

Related Topic