function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
College ManagementCollege Management 

Send Email with Generated PDF as attachment using schedule class ?

1. I've created an apex class and visualforce page to send given report to given email id as a pdf and xls attacments, working fine.
2. And i know " getContent() and getContentAsPdf() " is not supported for schedulable class. So to overcome it i created  schedule class which will call the previously created apex class to send a report. I am getting 2 attachments but it does not contains any content in it.

Thanks !
Gaurav NirwalGaurav Nirwal
This is complete process 
Schedule class:-
global class ScheduleFinacialNotification implements Schedulable {
global string sendSessionId;

global ScheduleFinacialNotification(String sessionId){
  this.sendSessionId = sessionId;
global void execute(SchedulableContext SC) {
     BatchSendFinacialNotification batchApex=new BatchSendFinacialNotification();
     batchApex.sessionId = this.sendSessionId;
     Database.executeBatch(batchApex,1);  }}

Batch class:-

global class BatchSendFinacialNotification implements Database.Batchable<sObject>,Database.Stateful,Database.AllowsCallouts {
public String query;
global string sessionId;
global BatchSendFinacialNotification(){
  this.sessionId  = sessionId;     
        query    = 'Select Id,Name,Project__r.Go_Live_Date__c from Service_Project_Junction__c ';
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
global void execute(Database.BatchableContext BC, List<Service_Project_Junction__c> scope) {
  //List<Service_Project_Junction__c> pojJunRecList = [Select Id,Name,Project__c,Opportunity_Deal__c,Project__r.Id,Project__r.Go_Live_Date__c,Product_Opportunity_Junction__r.Service__r.Service_Type__c,Product_Opportunity_Junction__r.Service__r.Product_Price__c,Product_Opportunity_Junction__r.No_Of_Months__c,Product_Opportunity_Junction__r.Total_Price__c,Product_Opportunity_Junction__r.No_Of_Listings__c from Service_Project_Junction__c where Opportunity_Deal__c != null AND Project__r.Go_Live_Date__c != null];
  for(Service_Project_Junction__c proRec: scope){
   Integer duration = integer.valueOf(proRec.Product_Opportunity_Junction__r.No_Of_Months__c);
   Integer totMonthTillToday = proRec.Project__r.Go_Live_Date__c.monthsBetween(;
   System.debug('Test in for loop==>'+proRec);
   if(totMonthTillToday <= duration && proRec.Project__r.Go_Live_Date__c.Day() =={
    System.debug(sessionId+'Test in if loop==>'+this.sessionId);
    ServiceInvoiceRedirectController.attachPdfToRecord( proRec.Project__r.Id, this.sessionId);
    System.debug('Test in if loop after condiyion==>');

global void finish(Database.BatchableContext BC){     

Call of REST Api class:-

global class ServiceInvoiceRedirectController
        global static void AttachPDFtoRecordREST()
            RestRequest req = RestContext.request;
            id recordId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

            PageReference pdfPage = new PageReference('/apex/ServiceInvoicePDF?Id='+recordId);
            Blob pdf = pdfPage.getContentAsPdf(); //!Test.isRunningTest() ? pdfPage.getContentAsPdf() : Blob.ValueOf('dummy text');
            Project__c prjRec = [Select Id,Name,Builder_Name__c from Project__c where Id =: recordId];
            //Insert Invoice record for related project
         Invoice__c invoRec = new Invoice__c();
         invoRec.RecordTypeId = Constants_PicklistVariables.serInvoice;
         invoRec.Project__c = recordId;
         invoRec.Account__c = prjRec.Builder_Name__c;
         insert invoRec;
         }catch(Exception e){
         //Insert Attacment to the invoice      
         Attachment a = New Attachment();
         a.body = pdf;
         a.parentID =;
         a.ContentType  = 'application/pdf';
         a.Name = 'SER-INV-''.pdf';
         insert a;
         }catch(Exception e){
         //Create the email attachment
      Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
      efa.setFileName('pdfName.pdf');//Pleace ad pdf name from contact name project and oppty concatinate
      // Create the Singal Email Message
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
      email.setSubject('Financial Notification');
      email.setToAddresses(new String[] { '' });//add account email id
      email.setPlainTextBody( 'Please Find Attachment your financial report Attached with this email.');
      email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
      // Sends the email
      Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

        // call this method from your Batch Apex
        global static void attachPdfToRecord( Id recordId, String sessionId )
         System.debug('Iam in REST API Call method');
           // String addr = '' + recordId;
            HttpRequest req = new HttpRequest();
            req.setHeader('Authorization', 'OAuth ' + sessionId);

            Http http = new Http();
            HttpResponse response = http.send(req);  

Schedule class from Developer Console in Anonymous Window:-

Datetime sysTime =;
sysTime = sysTime.addSeconds(5);
String chron_exp =' '+sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + + ' ' + sysTime.month() + ' ? ' + sysTime.year();
System.schedule('Job1',chron_exp , new ScheduleFinacialNotification(UserInfo.getSessionId()));

College ManagementCollege Management
Thanks Matthews ! I did it using trigger instead of batch class.