Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Prevent Large Data Queries in Salesforce with Transaction Security Policies
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • How to Confidently Manage Transactions in Salesforce Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Monday, August 11
    • Home
    • Salesforce Platform
      • Architecture
      • Apex
      • Lightning Web Components
      • Integration
      • Flows & Automation
      • Best Practices
      • Questions
      • News
      • Books Testimonial
    • Industries
      • Artificial Intelligence
    • Hire Me
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Downloads
      • Salesforce Release Notes
      • Apex Coding Guidelines
    • About Us
      • Privacy Policy
    • Contact Us
    SalesforceCodex
    Home»Salesforce»Sending Report As Attachment in Salesforce

    Sending Report As Attachment in Salesforce

    Dhanik Lal SahniBy Dhanik Lal SahniApril 8, 2020Updated:May 12, 202026 Comments3 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Sending Report As Attachment in Salesforce
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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.

    1. Create attachment using SOQL and add data as attachment
    2. Create attachment using Apex from standard report
    3. 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.

    Sample Report:

    apex lighting report salesforce
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleCOVID19 Live Chart in Lightning Web Component
    Next Article Salesforce Summer ’20 Release Postponed
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni6 Mins Read

    Prevent Large Data Queries in Salesforce with Transaction Security Policies

    August 11, 2025
    By Dhanik Lal Sahni6 Mins Read

    How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI

    July 28, 2025
    By Dhanik Lal Sahni7 Mins Read

    Top Mistakes Developers Make in Salesforce Apex Triggers

    July 25, 2025
    View 26 Comments

    26 Comments

    1. Sirisha on August 4, 2020 11:38 am

      This is very helpful. Thank you.

      Reply
      • Dhanik Lal Sahni on August 6, 2020 1:26 pm

        Thank You @Sirisha

        Reply
    2. Prabakaran on September 1, 2020 12:58 pm

      Great! Worked. Thank you!

      Reply
      • Dhanik Lal Sahni on September 5, 2020 11:05 am

        Thank You @Prabakaran

        Reply
    3. Jill on October 10, 2020 3:15 am

      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?

      Reply
      • Dhanik Lal Sahni on October 10, 2020 12:58 pm

        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

        Reply
    4. Jey on January 12, 2021 7:43 pm

      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.

      Reply
      • Dhanik Lal Sahni on February 14, 2021 9:51 pm

        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

        Reply
    5. Amit on February 18, 2021 1:58 pm

      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

      Reply
      • Dhanik Lal Sahni on February 18, 2021 5:03 pm

        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

        Reply
    6. Sumathi on May 25, 2021 3:39 pm

      how we can schedule this report through apex class? i know schedule apex but it’s not working.

      Reply
      • Dhanik Lal Sahni on June 5, 2021 7:38 pm

        Hello Sumathi,

        Are you getting any error? Please connect on LinkedIn or telegram group to resolve issue.

        Thank you,
        Dhanik

        Reply
    7. Sumathi on May 26, 2021 9:10 pm

      HI Dhanik,

      How we can schedule this second requirement? Please help me

      Reply
      • Dhanik Lal Sahni on May 26, 2021 9:29 pm

        Hello Sumathi, Please check above response. Thank You.

        Reply
    8. Sumathi on May 26, 2021 9:13 pm

      Hi Dhanik,

      for this solution Create attachment using Apex from standard report, How we can schedule?

      Reply
      • Dhanik Lal Sahni on May 26, 2021 9:28 pm

        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

        Reply
    9. Sumathi on June 7, 2021 3:01 pm

      Can you please provide test classes for those apex classes?

      Reply
    10. Nagendra Kumar Chavva on October 6, 2021 12:56 pm

      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?

      Reply
      • Dhanik Lal Sahni on December 7, 2021 12:57 pm

        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

        Reply
    11. Trinetra on March 3, 2022 9:44 pm

      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?

      Reply
      • Dhanik Lal Sahni on March 4, 2022 7:42 pm

        Ideally, you will not get any errors. Let me know if you are getting any errors.

        Thank You,
        Dhanik

        Reply
    12. Viviana on May 5, 2022 6:53 pm

      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.

      Reply
      • Dhanik Lal Sahni on May 6, 2022 6:33 am

        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

        Reply
    13. Tejal Meshram on November 13, 2023 5:50 pm

      can anyone know how to do it with excel file??

      Reply
      • Dhanik Lal Sahni on November 15, 2023 3:34 pm

        Hello Tejal,

        Please refer our other post Export Data from Lightning Web Component to Excel Sheet for excel.

        Thank You,
        Dhanik

        Reply
    Leave A Reply Cancel Reply

    Ranked #1 Salesforce Developer Blog by SalesforceBen.com
    SFBenTopDeveloper
    Ranked #4 Salesforce Developer Blog by ApexHours.com
    ApexHoursTopDevelopers
    Categories
    Archives
    Tags
    apex (117) apex best practices (5) apex code best practice (10) apex code optimization (6) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (24) salesforce (151) salesforce apex (53) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (5) salesforce news (5) salesforce question (5) security (4) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    MailChimp

    Expert Salesforce Developer and Architect
    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Prevent Large Data Queries in Salesforce with Transaction Security Policies
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 10 Salesforce CRM Trends to Watch in 2025 July 18, 2025
    • Discover the Top 10 Salesforce AppExchange Apps to Boost Productivity July 10, 2025
    • Top 20 Salesforce Data Cloud Interview Questions & Answers for Admins June 5, 2025
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    Archives
    Categories
    Tags
    apex (117) apex best practices (5) apex code best practice (10) apex code optimization (6) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (24) salesforce (151) salesforce apex (53) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (5) salesforce news (5) salesforce question (5) security (4) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.