Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Salesforce by (11.9k points)

I have a sales force report and what I want is to schedule this report in csv format on daily basis so that the user gets mail with this attachment.

1 Answer

0 votes
by (32.1k points)

You can schedule the report using the following code:

global class ExporterCSV implements System.Schedulable {

global void execute(SchedulableContext sc) {

List<Merchandise__c> acclist = [Select id , name , CreatedDate , lastModifiedDate from Merchandise__c limit 10];

string header = 'Record Id , Name , Created Date , Modified Date \n';

string finalstr = header ;

for(Merchandise__c a: acclist)

{

   string recordString = a.id + ',' + a.Name + ',' + a.CreatedDate + ',' + a.LastModifiedDate + '\n';

   finalstr = finalstr + recordString;

}

Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();

blob csvBlob = Blob.valueOf(finalstr);

string csvname= 'Invoice.csv';

csvAttc.setFileName(csvname);

csvAttc.setBody(csvBlob);

Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();

String[] toAddresses = new list<string> {'[email protected]'};

String subject = 'Merchandise Report CSV';

email.setSubject(subject);

email.setToAddresses( toAddresses );

email.setPlainTextBody('The Merchandise report is attached here.');

email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});

Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

  }

}

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...