Wednesday, March 22, 2017

Email Salesforce Reports to External User.

Salesforce allow only to send reports to User or Contact Emails. Some situations we have to send the reports to External emails, which are not part of Salesforce User or Contact.  Using apex code we can send the Salesforce reports to external emails as an excel attachment.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
String reportId = ''; // Set the report id that to be send
String requestUrl = '/' + reportId;
       requestUrl += '&excel=1';
Blob reportContent = new PageReference(requestUrl).getContent();
String reportData = reportContent.toString();

// To create an Excel report, we have to extract only the html table content
String excelContent = '';
if(reportData.contains('<div class="reportOutput">')){
 excelContent =  reportData.substringAfter('<div class="reportOutput">');
 excelContent =  excelContent.substringAfter('<table ');
 excelContent =  '<table '+excelContent.substringBefore('</table>')+'</table>';
}
  
// Define the email
String[] toAddresses = List<String>('email@sfdc.com');
String templateBody = 'Please see the attached Report';
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

// Sets the paramaters of the email
email.setSubject( 'The Status Report' );
email.setToAddresses( toAddresses );
email.setPlainTextBody(templateBody);

// Create the email attachment with a file name.
Messaging.EmailFileAttachment excelAttach = new Messaging.EmailFileAttachment();
excelAttach.setFileName('Report_'+Datetime.now().getTime()+'.xls');
excelAttach.setContentType('application/vnd.ms-excel; charset=utf-8');
excelAttach.setBody(Blob.valueOf(excelContent));
email.setFileAttachments(new Messaging.EmailFileAttachment[] {excelAttach});

// Sends the email
Messaging.SendEmailResult [] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); 
if (results.size()>0 && !results.get(0).isSuccess()) {
 system.debug(results.get(0).getErrors()[0].getMessage());
}  


1 comment: