Tuesday, April 7, 2015

How to generate weekly report and sent it as a attachment in mail in Salesforce?

Problem:
 We can generate reports as per our requirement using standard Report Builder Functionality.
With report builder we can create reports ,run reports and even we can schedule and send through mails.


The problem is we can get report as body of the mail not as attachment .

 

Solution:

With  Apex Code we can send reports as attchemnts. This is ideal, because you can have the code run weekly, scheduled inside your salesforce.com instance. No visualforce necessary in this case, because the results could be emailed or submitted to an HTTP server (not FTP, because Apex Code can't yet do that).
  Below is the sample code which gets content from Report and prepares an attachment to send through mail.
  It implements System.Schedulable interface so we can schedule this class to run weekly or monthly.
 

global class Accounts_Weekly_Report implements System.Schedulable {
    global void execute(SchedulableContext sc) {
        ApexPages.PageReference report = new ApexPages.PageReference('/00OF0000006WD6L?csv=1');
        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
        attachment.setFileName('Accounts_Weekly_Report.csv');
        attachment.setBody(report.getContent());
        attachment.setContentType('text/csv');
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
        message.setSubject('Accounts Weekly Report');
        message.setPlainTextBody('The report is attached.');
        message.setToAddresses( new String[] { 'abc1@test.com','abc2@test.com' } );
        message.setCcAddresses(new String[] { 'abc3@test.com'});
        Messaging.sendEmail( new Messaging.SingleEmailMessage[] { message } );
        
    }
    }


Thanks,
Naveen.
www.autorabit.com 

3 comments: