I need to write a trigger that sends out an email notification whenever an account, lead, and contact is deleted. Also, what is the best test class to write in order to get 100% code coverage?

Here is the code:

trigger EmailAfterDelete on Account(after delete) {
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
    for (Account acct : Trigger.old) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] {'naushadparpia@gmail.com'});
        email.setSubject('Deleted Account Alert');
        email.setPlainTextBody('This message is to alert you that the account named ' + acct.Name + ' has been deleted.');

Here is the error that I am getting every time I try to delete an account:

Validation Errors While Saving Record(s) There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger EmailAfterDelete caused an unexpected exception, contact your administrator: EmailAfterDelete: execution of AfterDelete caused by: System.NoAccessException: The organization is not permitted to send email: Trigger.EmailAfterDelete: line 2, column 1".

  • welcome to salesforce.stackexchange Matt. I've used the {} button in the editor to format the code in your question. Please try to keep questions specific to a single issue. Lets first focus on avoiding that error, we can worry about test classes later (there are many good resources around). – Samuel De Rycke Sep 15 '14 at 19:52

For the error that you have encountered just set the access level of 'access to send emails' to 'all emails'.

Go to setup > administration setup > email administration > deliverability > set access level to all emails.

Update : for your second question i.e. to get 100% test coverage write a test class. Create a dummy test account in that test class and then delete that dummy test account. The trigger will fire after deletion of dummy test account and your trigger will be covered for test coverage.

| improve this answer | |
  • 1
    Hi @Matt If this answer helps you, please mark the answer as the right one so we can close the question. – A-d Sep 15 '14 at 20:33

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.