0

Although I've defined setPlainTextBody, it throws the error: First error: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Email body is required.: []

global class OppStatusNotification_Batch implements Database.Batchable{

global Database.QueryLocator start(Database.BatchableContext BC)
{

    String query = 'Select Id, Name, StageName, Owner.Email from Opportunity';
    return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Opportunity> scope)
{

    String messageBody;
    for(Opportunity opp : (List<Opportunity>)scope){
        if(opp.StageName == 'Submitted to Manager'){
            messageBody = 'This application was submitted to Manager.';
        }

        else if(opp.StageName == 'Declined by Manager'){
            messageBody = 'This application was declined by Manager'.;

        }

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {opp.Owner.Email};
        email.setToAddresses(toAddresses);
        email.setSubject('Opportunity Name: ' + opp.Name);
        email.setPlainTextBody(messageBody);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}

global void finish(Database.BatchableContext BC)
{

}

}

1

If the stage is not either "Submitted to Manager" or "Declined by Manager", then messageBody will be null, thus producing this error. Consider filtering your batch process to filter opportunities by only one of those two stages.

2
  • actually there are 5 more values for which the email has to be sent. Would it be okay to filter opportunities with those values ?
    – ngc
    Apr 12 '18 at 0:00
  • @ngc Yes, just make sure that you're not processing records that will not be used.
    – sfdcfox
    Apr 12 '18 at 0:01

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.