Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are HTML emails being sent by a APEX Schedulable class being delivered with blank bodies?

I have an APEX class that is used to send an email out each day at 7PM:

global class ReportBroadcaster implements Schedulable {

    global ReportBroadcaster() {
    }

    global void execute(SchedulableContext sc) {
      send();
    }

    global void send() {
      PageReference page = new PageReference('/apex/nameofvfpage');
      page.setRedirect(true);
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
      email.setSubject('Example Subject');
      email.setHtmlBody(page.getContent().toString());
      email.setToAddresses(new String[]{'[email protected]'});
      Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});     
    }
}

When I execute the send() method via an instance of the ReportBroadcaster via anonymous APEX, it is delivered as expected. However, when I schedule the class, the email is delivered with a blank body. If I switch the email body to plain text, it delivers fine (but that doesn't work for me).

How do I make this work?

UPDATE:

You cannot call getContent() on PageReference instances from either scheduled APEX or @future methods (I'm not sure why that would be, but it is what it is). I think that the solution will be to create a web service that I'll call from the @future method. Seems incredibly hacky, but I'm not sure what else I could do.

FINAL UPDATE: This is how to send HTML emails from scheduled APEX:

  • Create a class that implements the Schedulable interface.
  • Have the execute() method call an @future method.
  • Have the @future method call a web service enabled method in the class that sends the email.

While this approach is roundabout, it works.

like image 283
barelyknown Avatar asked Feb 22 '12 23:02

barelyknown


1 Answers

getContent() method is not supported in scheduled Apex. See the last line of this page:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_scheduler.htm

like image 90
naomi Avatar answered Nov 15 '22 07:11

naomi