6

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);
  • Welcome to the community! You may be asked for a code sample so we can see how you're using the template; can you provide that? – Mike Chale Feb 28 '13 at 17:28
  • Are you using trigger.old? I suspect this is your problem. Could you post your code? – greenstork Feb 28 '13 at 17:33
  • 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); – Ivano Feb 28 '13 at 17:39
  • Hard to tell without seeing more of your code, like the emails object and the prepare email method in it's entirety. – greenstork Feb 28 '13 at 17:52
  • @Ivano: If LaceySnr answered your question please mark his response as the answer. – Mike Chale Mar 1 '13 at 13:50
1

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.

1

Thank you @LaceySnr, you were right, the problem was due to the fact that the send email method was separated from the if(Trigger.isDelete){} section and the record was already deleted at sending time. I solved the issue preventing the record deletion by revaluate if(Trigger.isDelete){ system.debug('xxx');}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.