[SalesForce] issue adding csv file attachment to email in Batch job

In a batch file we are updating records, and for each one we are creating a record which is sent in an email when the batch completes.

It all works swimmingly except that the csv file is sent as an HTML file with the name UpdatedEntityrecords.csv.html

This is very strange, as nowhere in my code do I append the word .html to the filename…

here is the code where the work is done:

    string sEmailBody='Please see the attached file for details of the ' + RecordNo + ' records updated.';
    if (iErrorsCount > 0){
        sEmailBody+='\n\nThere were '+iErrorsCount +' errors during the batch';        
    }       

    sEmailBody += '\n\nThis email was sent by the batch job \'BATCH_Ent_Update_Eqn_Status\' ';

    string csvHeader='Id, Name, Cif ID, TimeStamp, LastModifiedDate, Errors\n';
    csvData = csvHeader + csvData;

    Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();

    system.debug('Send email');

    if (RecordNo>0){
        //Create csv attachment
        system.debug('add csv file attachment');     
        blob csvBlob = Blob.valueOf(csvData); //updatedEntities
        string csvname= 'UpdatedEntityrecords.csv';
        csvAttc.setFileName(csvname);
        csvAttc.setBody(csvBlob);            
    }

    //Create Email      
    Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
    String[] toAddresses = new list<string> {'theTeam@ourLittleBank.co.uk'}; 
    String[] ccAddresses = new list<string> {'aPerson@ourLittleBank.co.uk'}; 

    email.setSenderDisplayName('Entity records Equation status Batch job');
    email.setSubject('Entity records Equation status updated');       

    email.setToAddresses( toAddresses );
    email.setCcAddresses( ccAddresses );        

    if (RecordNo>0){
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});    
        email.setPlainTextBody(sEmailBody);
    }else email.setPlainTextBody('No records were updated by the batch process');        

    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    system.debug('email sent');

so is there something else I need to do in order to have the attachment put on as a csv file, instead of a …csv.html?

Best Answer

This should be because you are not setting contentType of attachment. And set filename as well by setFileName(String fileName) method.

if (RecordNo>0)
{
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvBlob }); 
        email.setContentType('text/csv');   
        email.setPlainTextBody(sEmailBody);
}

Also,csvBlob needs to be passed instead of csvAttc.

Related Topic