+ Start a Discussion
Soubhagya Ranjan 2Soubhagya Ranjan 2 

unable to send email

i have a trigger which shows error while trying to delete a record . it is working fine but after that the requirement is to send email to owner of that record . it is not working . i am posting my code . please check and provide the solution .

Trigger : 
Trigger ErrorDelete on Course__c(before delete) {
    Messaging.reserveSingleEmailCapacity(trigger.size);
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
    for (Course__c c: Trigger.old) {
        c.adderror ('can not delete');
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] {'ranjan.soubhagya2015@gmail.com'});
        email.setSubject('Deleted Account Alert');
        email.setPlainTextBody('This message is to alert you that the account  has been deleted.');
        emails.add(email);
    Messaging.sendEmail(emails);
        
    }
    
}




whenever i am commenting the adderror line then mail is sending but at a time error showing and email sending not working 
Shun KosakaShun Kosaka
Set sendEmail method out of for loop.
Trigger ErrorDelete on Course__c(before delete) {
    Messaging.reserveSingleEmailCapacity(trigger.size);
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
    for (Course__c c: Trigger.old) {
        c.adderror ('can not delete');
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] {'ranjan.soubhagya2015@gmail.com'});
        email.setSubject('Deleted Account Alert');
        email.setPlainTextBody('This message is to alert you that the account  has been deleted.');
        emails.add(email);
    }
     Messaging.sendEmail(emails);
}
I tried this on Contact (because I don't have the custom object) with my email address and commenting the adderror line. And it works!
 
Soubhagya Ranjan 2Soubhagya Ranjan 2
Hi Shun ,

by commenting adderror line email is sent .
but by not commenting that line email is not sent .
 
Shun KosakaShun Kosaka
Hi Soubhagya,
Sorry for misunderstanding... Unfortunately, the adderror method prevents all transactions from committing including emails.

See also,
http://salesforce.stackexchange.com/questions/82544/sending-email-on-validation-failure