+ Start a Discussion

How to cover email send error

Looking to get coverage for the else part:
message.subject = messageSub;
        message.plainTextBody = messageBody;
        Messaging.SingleEmailMessage[] messages = 
            new List<Messaging.SingleEmailMessage> {message};
                Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        if (results[0].success) {
            System.debug('The email was sent successfully.');
        } else {
            System.debug('The email failed to send: '
                + results[0].errors[0].message);

SwethaSwetha (Salesforce Developers) 
HI Colbridge,

To cover the Email exception block you need to throw an exception explicitly if its in a Test context, sample below:
if(Test.isRunningTest()) {
    throw new EmailException('Email Exception occurred for testing'); 
This will get caught in the EmailException catch and will cover that block.

Reference: https://salesforce.stackexchange.com/questions/163994/test-class-for-bounced-email-try-catch-coverage

Related: https://salesforce.stackexchange.com/questions/96572/how-to-test-sendemailresult-for-singleemailmessage 

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you