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
Leafen SandyLeafen Sandy 

Scheduler apex class to run and email reports

Hi,

My exact requirement is as follows,

I have a custom object, say myreports__c, where in each record user will choose a report name in a lookup field and will have a time field, an email field and a date field.

So, now I've to query these records each day which has the today's date in the date field and need to run and email the selected report in those records at the mentioned time.

Even a sample or suggestive code will be greatly helpful.

Thanks,
Leafen Sandy
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi leafen,

May I request you to please refer the below link for reference. I hope it will be helpful.

Please mark it as best answer if the information is informative.so that they are removed from unanswered questions and more app as a proper solution to Similar kind of Issue.

Best Regards
Rahul Kumar
Ankur Saini 9Ankur Saini 9
Hi Leafen,

We can't create lookup field with report object. You have to create a dynamic picklist on vf page for this.

try this: 

VF Page:
<apex:page standardController="Report_Scheduler_Setup__c" extensions="reportExt">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
                <apex:outputLabel >Report Name</apex:outputLabel>  
                <apex:selectList size="1" value="{!repID}">
                    <apex:selectOptions value="{!listOfreport}"></apex:selectOptions>            
                </apex:selectList>
            </apex:pageBlockSectionItem>
            <apex:inputField value="{!rs.Date__c}"/>
            <apex:inputField value="{!rs.Time__c}"/>            
            <apex:inputField value="{!rs.Email_ID__c}"/>
        </apex:pageBlockSection> 
        <apex:commandButton value="Save" action="{!mySave}"/>       
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex Controller:
public with sharing class reportExt {
public string repID{get;set;}
public Report_Scheduler_Setup__c rs{get;set;}
public list<selectoption> listOfReport{get;set;}

    public reportExt(ApexPages.StandardController controller) {
        rs=new Report_Scheduler_Setup__c();
        listOfReport = new list<selectoption>();        
        listOfReport.add(new selectoption('','--None--'));
        for(Report repObj : [select id,name from Report limit 1000]){
            listOfReport.add(new selectoption(repObj.id,repObj.name));
        }
    }
    
    public pagereference mySave(){ 
    try{   
        rs.Report_ID__c=repID;
        insert rs;
        
        if(rs.Date__c!=null && rs.Time__c!=null && rs.Email_ID__c!=null && rs.Report_ID__c!=null){
            ScheduleReport sr = new ScheduleReport();
                sr.reportId=repID;
                sr.email=rs.Email_ID__c;
                
                string sch = '0 0 '+rs.Time__c+' '+rs.Date__c.day()+' '+rs.Date__c.month()+' ?'; 
                system.schedule('Job', sch, sr);
            }
        }
        catch(DMLException ex){}
        return null;
    }
    
    @future(callout=true)
    public static void sendEmail(string reportId,string email){
        List<Report> repList = [Select id,name from report where id=:reportId limit 1];
    if(repList.size()>0){
        ApexPages.PageReference report = new ApexPages.PageReference('/'+repList[0].id+'?csv=1');
        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
        attachment.setFileName(repList[0].name+'.csv');
        attachment.setBody(report.getContent());
        attachment.setContentType('text/csv');
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
        String[] toAddresses=email.split(',');       
        message.setSubject(repList[0].name+' Report');
        message.setPlainTextBody('The report is attached.');
        message.setToAddresses(toAddresses);
        Messaging.sendEmail( new Messaging.SingleEmailMessage[] { message } );
        }
    
    }

}

Scheduler Class
global class ScheduleReport implements System.Schedulable {
global string reportId;
global string email;

    global void execute(SchedulableContext sc) {
    
        reportExt.sendEmail(reportId,email);
        }
    }

​​Thanks,
Ankur Saini
http://mirketa.com
Leafen SandyLeafen Sandy
Hi Ankur,

Thanks for your help,

But here I like to make myself even more clear, I've already created the vf page and controller to insert records having the chosen report with desired email, date and time.

So now my only part is to create a scheduler class which should pick these records from that object and run the report given in it and email that report.(Also I need to receive the report in the body of the mail like the standard functionality, not as an attachment).

So kindly guide me through from here.

Thanks,
Leafen.