Sunday, January 8, 2017

Productivity: Case email bounce back analysis by querying, parsing result and printing to CSV from Salesforce.com Developer console

Use-case: Case email bounce back analysis by querying, parsing the result and printing to CSV using a single code snippet from Salesforce.com Developer console #Productivity

What the following sample script does?: 1) Queries for the undelivered emails resulted in cases created via "Email to case".
 2) Parses the bounced emails from the result
 3) Prints the modified results on CSV which will be stored in Salesforce.com Files.
 4) The code can be run from salesforce.com developer console in a short time and does not need to be maintained on the salesforce.com platform.

Sample script:
String csv = 'Id,Description,EmailAddress\n';
          String regex = '>>> ([a-zA-Z0-9_\\-\\.]+)@(((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3}))';
         Pattern myPattern = Pattern.compile(regex );

for ( Case cas : [ Select Id,Description
from Case
where <<filter conditions>>
order by createddate asc limit 10]
) {
Matcher myMatcher = myPattern.matcher(acct.description.escapeCsv());
if (myMatcher.find())
       csv += cas.id + ',' + cas.description.escapeCsv() + ',' + myMatcher.group().split('>>> ')[1].trim() + '\n';
else
      csv += cas.id + ',' + cas.description.escapeCsv() + ',' + '' + '\n';

}

ContentVersion file = new ContentVersion(
title = 'cases.csv',
versionData = Blob.valueOf( csv ),
pathOnClient = '/cases.csv'
);

insert file;
System.debug('this is file:' + file );