How to send CSV attachment in apex code

By | February 18, 2022

In this blog, we will discuss How to send csv attachment in apex code.

Here, we are going to see how create a csv file with code and then we will send that file as attachment to the mail with the help of the apex code.

Apex logic to send the csv attachment with mail:

public static map<String,String> SendMail()
{
    map<String, String> result = new map<String, String> ();
    String csv = 'Id,Name\n';
    for ( List<Account> accts : [ SELECT id, name FROM Account LIMIT 10 ] ) 
    {
        for ( Account acct : accts )
        {
            csv += acct.id + ',' + acct.name.escapeCsv() + '\n';
        }
    }
    result = SendCsvEmail(csv);
    return result;
} 
  
public static map<String,String> SendCsvEmail(String CsvData)
{
    System.debug('CsvData' +CsvData); 
    map<String, String> result = new map<String, String> ();
    try{
        Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
        Blob csvBlob = blob.valueOf(CsvData);
        String csvName = 'CsvFileName.csv';
        csvAttachment.setFileName(csvName);
        csvAttachment.setBody(csvBlob);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'test@test.com'};
            String subject = 'Test CVS Email';
        email.setSubject(subject);
        email.setToAddresses(toAddresses);
        email.setPlainTextBody('Test CSV Email');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
        Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
        if (r[0].success) {
            System.debug('The email was sent successfully.');
            result.put('SUCCESS', 'The email was sent successfully.');
        } else {
            System.debug('The email failed to send: ' + r[0].errors[0].message);
            result.put('ERROR', 'The email failed to send: ' + r[0].errors[0].message);
        }
    }
    catch(Exception EX)
    {
        System.debug('The email failed to send: ' + Ex.getMessage());
        result.put('ERROR', 'The email failed to send: ' + Ex.getMessage());
    }
    return result;
}

We hope using the information; you are able to create and send csv attachment with an email.

Note: – Replace test@test.com with the email address where you want to send the email.

We hope you may find this blog resourceful and helpful. If you still have concerns and need more help, don’t hesitate to get in touch with us at salesforce@greytrix.com.

About Us
Greytrix – a globally recognized and one of the oldest Sage Development Partner and a Salesforce Product development partner offers a wide variety of integration products and services to the end users as well as to the Partners and Sage PSG across the globe. We offer Consultation, Configuration, Training and support services in out-of-the-box functionality as well as customizations to incorporate custom business rules and functionalities that require apex code incorporation into the Salesforce platform.

Greytrix has some unique solutions for Cloud CRM such as Salesforce Sage integration for Sage X3Sage 100 and Sage 300 (Sage Accpac). We also offer best-in-class Cloud CRM Salesforce customization and development services along with services such as Salesforce Data MigrationIntegrated App developmentCustom App development and Technical Support to business partners and end users.
Salesforce Cloud CRM integration offered by Greytrix works with Lightning web components and supports standard opportunity workflow. Greytrix GUMU™ integration for Sage ERP – Salesforce is a 5-star rated app listed on Salesforce AppExchange.

The GUMU™ Cloud framework by Greytrix forms the backbone of cloud integrations that are managed in real-time for processing and execution of application programs at the click of a button.

For more information on our Salesforce products and services, contact us at salesforce@greytrix.com. We will be glad to assist you.

Related Posts