function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Michael MMichael M 

Issue with code emailing report

Hello, I am need to send one of our reports via csv. I am trying through apex with this code:

global class ReportEmailCharles implements system.Schedulable {
 global void execute(SchedulableContext sc) {
        ApexPages.PageReference report = new ApexPages.PageReference('/00O63000000uP8GEAU?csv=1');
        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
        attachment.setFileName('report.csv');
      attachment.setBody(Blob.valueof(report.getContent().toString()));
        attachment.setContentType('text/csv');
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
        message.setSubject('Overall Pull- 2 All');
        message.setPlainTextBody('Overall Pull- 2 All');
        message.setToAddresses( new String[] { 'mm@abc.org' } );
        Messaging.sendEmail( new Messaging.SingleEmailMessage[] { message } );
        
    }
}

The 18 character id of the report I'm testing is 00O63000000uP8GEAU

However the "csv" excel doc of the email I receive looks like this:

User-added image
Anything I can change in my code to make this work?
Best Answer chosen by Michael M
AbhishekAbhishek (Salesforce Developers) 
Can you go through the suggestions as per the below blogs,

https://developer.salesforce.com/forums/?id=906F00000008n0zIAA

https://salesforce.stackexchange.com/questions/337/can-report-data-be-accessed-programatically

This Release notes (https://releasenotes.docs.salesforce.com/en-us/summer20/release-notes/rn_rd_reports_subscribe_attachment.htm)mentions "Attach .csv Files to Report Subscriptions (Still in Beta Verison)"

I hope you find the above information is helpful. If it does, please mark as Best Answer to help others too.

Thanks.

All Answers

AbhishekAbhishek (Salesforce Developers) 
Can you go through the suggestions as per the below blogs,

https://developer.salesforce.com/forums/?id=906F00000008n0zIAA

https://salesforce.stackexchange.com/questions/337/can-report-data-be-accessed-programatically

This Release notes (https://releasenotes.docs.salesforce.com/en-us/summer20/release-notes/rn_rd_reports_subscribe_attachment.htm)mentions "Attach .csv Files to Report Subscriptions (Still in Beta Verison)"

I hope you find the above information is helpful. If it does, please mark as Best Answer to help others too.

Thanks.
This was selected as the best answer
Michael MMichael M
Awesome- thank you. I used the tip from the release notes and it looks like it is working
Sahana Shekar 7Sahana Shekar 7
Hi team,

I am still getting this error which is mentined by michael.
This functionality was working fine till yesterday and suddenly this has stopped working in prod.
This still works well in full sandbox. I have not changed any settings in prod.
Please let me know if there is any other option to improve my code.
The email with attachment has to go to an entire group under the custom label. Please help.

Thanks
Sahana
Michael MMichael M
Hi Sahana, 

Are you using apex to send the report, or the native csv attachment feature (https://releasenotes.docs.salesforce.com/en-us/summer20/release-notes/rn_rd_reports_subscribe_attachment.htm)?
Sahana Shekar 7Sahana Shekar 7
Yes i am using it.
I want to use the same feature rather than the subscribing way.
 
Michael MMichael M
For this feature I am personally using the subscribe feature. However, I have also been able to successfully send a csv file via email with apex using the below code. Instead of querying a report, you query for the actual fields you want to send. You can edit the below to fit your requirement, and use in scheduled apex. 


// fetch Data using SOQL from Salesforce
List<Contact> contList = [Select id, name, CreatedDate, lastModifiedDate, email from Contact where email != null limit 10];
//Set Header values of the file
string csvHeader = 'Record Id, Name, Created Date, Modified Date, Email Address \n';
string mainContent = csvHeader;
for (Contact cnt: contList){
      //Adding records in a string
       string recordString = cnt.id+','+cnt.Name+','+cnt.CreatedDate+','+cnt.LastModifiedDate +','+cnt.email +'\n';
       mainContent += recordString;
}
Messaging.EmailFileAttachment csvAttcmnt = new Messaging.EmailFileAttachment ();

//Create CSV file using Blob
blob csvBlob = Blob.valueOf (mainContent);
string csvname= 'Contact.csv';
csvAttcmnt.setFileName (csvname);
csvAttcmnt.setBody (csvBlob);
Messaging.SingleEmailMessage singEmail = new Messaging.SingleEmailMessage ();
String [] toAddresses = new list<string> {'test@test.org'};
//Set recipient list
singEmail.setToAddresses (toAddresses);
String subject ='Contact CSV';
singEmail.setSubject (subject);
singEmail.setPlainTextBody ('Contact CSV');

//Set blob as CSV file attachment
singEmail.setFileAttachments (new Messaging.EmailFileAttachment []{csvAttcmnt});
Messaging.SendEmailResult [] r = Messaging.sendEmail (new Messaging.SingleEmailMessage [] {singEmail