Recently my team got requirement to send report as email attachment to external users. This blog will show number of ways we can send report as attachment in email.
We can send report to our internal user using standard schedule report but we can not schedule to send email to external user.
Here are some options which can be used to solve this requirement.
- Create attachment using SOQL and add data as attachment
- Create attachment using Apex from standard report
- Create user and send to that user email
Create attachment using SOQL and add data as attachmentÂ
We can create CSV from data which is queried using SOQL. Then we can send that generated CSV file as attachment. Let us take example we need to share all account detail which are opened using our custom API . Here is code which will be used to share email with above mentioned data.
Steps:
1. Create SOQL
Create SOQL to get data from object. I have fetched 10 records from account. These will come as CSV records.
List<Account> acconts = [SELECT Id,Name,BillingState FROM Account LIMIT 10];
2. Convert data into CSV
Put all record data as string.
string header = 'Id, Account Name, BillingState\n'; string finalstr = header; if(acconts !=null && acconts.size()>0){ for(Account act: acconts) { string recordString = act.Id+','+act.Name+','+act.BillingState+'\n'; finalstr = finalstr +recordString; } }
3. Convert string data in CSV
Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment(); blob csvBlob = Blob.valueOf(attachFiles.get(name)); string csvname=name+'.csv'; csvAttc.setContentType('text/csv'); csvAttc.setFileName(csvname); csvAttc.setBody(csvBlob);
4. Send Email using EmailService class
Create a generic EmailService class. This class will send email to given user.
Complete Code:
Create attachment using Apex from standard report
We can send standard report as attachment as well. For this first create standard report and get report Id to be used in apex code.
Steps
1. Create SOQL
Get report detail using SOQL from Report object.
List <Report> reportList = [SELECT Id,DeveloperName,Name FROM Report where DeveloperName =:reportDevName]; String reportId = (String)reportList.get(0).get('Id'); //Get Report Name string reportName=(String)reportList.get(0).get('Name');
2. Get report content
Get report content using java servlet for specific report. Add report id from above mentioned step.
String instanceName = URL.getSalesforceBaseUrl().toExternalForm(); string url=instanceName+'/servlet/PrintableViewDownloadServlet?isdtp=p1&reportId='+reportId; ApexPages.PageReference objPage = new ApexPages.PageReference(url); Blob content=objPage.getContent(); //Get report content
3. Convert content into CSV
Convert blob into CSV file and add content into EmailFileAttachement.
Messaging.EmailFileAttachment objMsgEmailAttach = new Messaging.EmailFileAttachment(); objMsgEmailAttach.setFileName(reportName+'.csv'); objMsgEmailAttach.setBody(objPage.getContent()); objMsgEmailAttach.setContentType('text/csv');
Code:
Use EmailService class which is shown in first option’s code file.
Create user for external users and send to that user’s email
Refer solution outlined at Send a Scheduled Report Email to multiple addresses outside of Salesforce for this option.
26 Comments
This is very helpful. Thank you.
Thank You @Sirisha
Great! Worked. Thank you!
Thank You @Prabakaran
Can someone explain how I can test this code out. ?
I created the two classes EmailService and ReportGenerationController .
What do I need to do to see the output as shown in Sample Report?
Hello Jill,
You have to create standard report and you have to pass report developer name (API name) in ReportController.generateReport method. That will work.
Thank You,
Dhanik
Hi Dhanik
I am new to salesforce i created the class that you mentioned on “Create attachment using Apex from standard report”. so i added the report Api name to the method too. Now what should i do after this.
Hey Jey,
I have already provided information. Please tell me what is your issue so that I can explain you better. Ping me in twitter or linkedin for immediate resolution.
Thank You,
Dhanik
Hi Dhanik,
The given code renders the report in xls/xlsx format. Is there any parameter that we need to pass with the url which can render the report in csv format.
Setting only file extension or content type corrupts the report.
Appreciate your response.
Regards,
Amit Kumar
Hello Amit,
Have you tried complete code? if yes and not working, please ping me on linkedin or twitter. We will connect and sort out your issue.
Thank You,
Dhanik
how we can schedule this report through apex class? i know schedule apex but it’s not working.
Hello Sumathi,
Are you getting any error? Please connect on LinkedIn or telegram group to resolve issue.
Thank you,
Dhanik
HI Dhanik,
How we can schedule this second requirement? Please help me
Hello Sumathi, Please check above response. Thank You.
Hi Dhanik,
for this solution Create attachment using Apex from standard report, How we can schedule?
Hello Sumathi,
You can create schedulable class or add InvocableMethod in class. Schedule class can be scheduled from apex class page. InvocableMethod method you can schedule using flow. Try it and if you need help, ping me in linkedin or telegram group for immediate response.
Thank You,
Dhanik
Can you please provide test classes for those apex classes?
Can someone explain how I can test this code out. ?
I created the two classes EmailService and ReportGenerationController .
How to test it?
We don’t have any option to enter report name in these classes and when this will run?
Hello Nagendra,
You can call ReportController class from LWC/Aura component or from another controller to send the report. You can also test using an anonymous window.
Thank You,
Dhanik
If a scheduled report using any of these methods doesn’t return any records (let’s say on the third or fourth run) will we get an error?
Ideally, you will not get any errors. Let me know if you are getting any errors.
Thank You,
Dhanik
Hello, I created the EmailService and ReportGenerationController classes to send the csv of the 10 records of the account, in this case it is method 1, it does not throw me any error in the classes but I do not know how to prove that it works I am new in development.
Hello Viviana,
It should send a report with an attachment. Check you have entered the correct email in ReportController.apxc at lines # 38,39.
Thank You,
Dhanik
can anyone know how to do it with excel file??
Hello Tejal,
Please refer our other post Export Data from Lightning Web Component to Excel Sheet for excel.
Thank You,
Dhanik