Tuesday, February 3, 2015

Creating a CSV file from salesforce and sending through the Email

List<Account> lstAccount = [Select id,Name,CreatedDate from Account limit 10];
string header = 'Id, Name , Created Date \n';
string finalstr = header ;
for(Account acc: lstAccount)
{
       string recordString = '"'+acc.id+'","'+acc.Name+'","'+acc.CreatedDate+'"\n';
       finalstr = finalstr +recordString;
}

Messaging.EmailFileAttachment sendCsv = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(finalstr);
string fileName= 'Accounts.csv';
sendCsv.setFileName(fileName);
sendCsv.setBody(csvBlob);
Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
String[] toAddresses = new list<string> {'test@gmail.com'};
email.setSubject('Accounts');
email.setToAddresses( toAddresses );
email.setPlainTextBody('Accounts');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{sendCsv});
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

2 comments:

  1. I have one customer button in salesforce. When i would click on it, I want to download cvs on local. Is it possible?

    ReplyDelete
  2. Hi,

    You can download the csv file. Please find the below link to download the csv file

    http://sfdcintegration.blogspot.in/2015/10/download-csv-file-using-visual-force.html

    ReplyDelete