Hello Friends, today we will learn How to create or generate a csv file in apex code Salesforce and send this to email as attachments. Many times we need to send data files in email via apex code and csv files are the best things that we can easily show the data by column header.
Also check this: Reusable Datatable in Lightning Web Component(LWC) Salesforce
Code :
The below code will query all Account object records and send CSV files to email. In code I have put my email id you can replace it with your email Id.
CreateCSVFIleTechdicerCtrl.cls :
public class CreateCSVFIleTechdicerCtrl {
public static void createCsv(){
String csvColumnHeader;
List<String> csvRowValues = new List<String>();
String parentId;
for(Account acc : [SELECT Id, Name, Type, AccountNumber, CreatedDate FROM Account LIMIT 10]){
String formattedDate = acc.CreatedDate.format('M/d/yyyy h:mm:ss a z');
String accountName = acc.Name != null ? String.valueOf(acc.Name).escapeCsv() : '';
String accountType = acc.Type != null ? acc.Type : '';
String accountNumber = acc.AccountNumber != null ? acc.AccountNumber : '';
String csvRowVal = formattedDate + ',' + accountName + ',' + accountType + ',' + accountNumber;
csvRowValues.add(csvRowVal);
parentId = acc.Id;
}
csvColumnHeader = 'Date, Name, Type, Account Number\n';
String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');
//send email
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
Messaging.EmailFileAttachment attach1 = new Messaging.EmailFileAttachment();
blob b;
if(Test.isRunningTest()) {
b = blob.valueOf('Unit.Test');
} else {
b = Blob.valueOf(csvFile);
}
attach1.setFileName('test.csv');
attach1.setBody(b);
message.setFileAttachments(new Messaging.EmailFileAttachment[]{attach1});
String[] toAddresses = new String[] {'techdicerkeeplearning@gmail.com'};
message.setToAddresses(toAddresses);
message.setSubject('how-to-create-or-generate-a-csv-file-in-apex-salesforce-techdicer');
message.setHtmlBody('This email is for testing purpose of Create csv files');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { message });
}
}
Reference :
What’s your Reaction?
+1
2
+1
1
+1
+1
1
+1
6
+1