Salesforce: Send Email with File Attachments in CSV format

Sample code to send Email with File Attachments in CSV format

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses( new String[] { 'test@e.mail' } );
mail.setSubject( 'Test subject' );
mail.setHtmlBody( 'Test HTML Body' );
String contentCSV = '';
for ( Custom_Object__c co: [ SELECT Id, Field_1__c, Field_2__c FROM Custom_Object__c ]) {
	contentCSV += co.Id + ',' + co.Field_1__c + ',' + co.Field_2__c + '\n';
}
String content = 'Id, Field_1__c, Field_2__c\n' + contentCSV;
Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
attachment.setFileName( 'filename.csv' );
attachment.setBody( Blob.valueOf( content ) );
mail.setFileAttachments( new Messaging.EmailFileAttachment[]{ attachment } );
Messaging.sendEmail( new Messaging.SingleEmailMessage[] { mail } );

 

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s