2

I have written a Scheduler for sending an email which has a report as an attachment. I have scheduled the batch to run every day at 9 AM, however, I couldn't get the email. what seems to be the issue?

global class EmailReport implements System.Schedulable {
    global void execute(SchedulableContext sc) {
        ApexPages.PageReference report = new ApexPages.PageReference('/00O0I00000A8BcW?csv=1');
        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
        attachment.setFileName('report.csv');
        attachment.setBody(report.getContent());
        attachment.setContentType('text/csv');
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
        message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
         message.setSubject('Daily sales report');
        message.setPlainTextBody('The report is attached.');
        message.setToAddresses( new String[] { '[email protected]' } );
        Messaging.sendEmail( new Messaging.SingleEmailMessage[] { message } );

    }
}

Exception:

Apex script unhandled exception by user/organization: 00528000000bWsf/00D280000017TTr Scheduled job 'scheduleJob' threw unhandled exception. caused by: System.CalloutException: Callout from scheduled Apex not supported

1 Answer 1

2

Since Summer 15, getContent() is considered as a Callout. scheduler cant do a callout.

So you cannot directly call getContent from scheduler. You have to use a mashup of the scheduler and future apex.

global class EmailReport implements System.Schedulable {
    global void execute(SchedulableContext sc) {
        EmailReport.sendEmailViaFuture();

    }

    @future(callout=true)
    global static void sendEmailViaFuture(){
        ApexPages.PageReference report = new ApexPages.PageReference('/00O0I00000A8BcW?csv=1');
        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
        attachment.setFileName('report.csv');
        attachment.setBody(report.getContent());
        attachment.setContentType('text/csv');
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
        message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
         message.setSubject('Daily sales report');
        message.setPlainTextBody('The report is attached.');
        message.setToAddresses( new String[] { '[email protected]' } );
        Messaging.sendEmail( new Messaging.SingleEmailMessage[] { message } );
    }
}

source: https://releasenotes.docs.salesforce.com/en-us/summer15/release-notes/rn_vf_getcontent_callout_cruc.htm

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .