PradysTechBlog

Yet another blog

Read an email sent to salesforce and read them as records

I was asked to work on a requirement which required that an email is sent to salesforce and we would need to read through the email and create a new case based for each row in the email. This email is generated from a external SQL server and emailed everyday

Here is the sample email

11111|Case1|AC123|Ac_001|9|4|Wed Aug 10 09:02:03 2011|1|completed

11112|Case2|AC123|Ac_001|9|4|Wed Aug 10 09:02:03 2011|1|completed

11113|Case3|AC123|Ac_001|9|4|Wed Aug 10 09:02:03 2011|1|completed

11114|Case4|AC123|Ac_001|9|4|Wed Aug 10 09:02:03 2011|1|completed

11115|Case5|AC123|Ac_001|9|4|Wed Aug 10 09:02:03 2011|1|completed

Go go the solution, first we must create a email service which will create an email id to which the emails are to be sent.

You can create the email service by going to Setup->Develop->email services

Before you create the email service we would need to create a class which this email service would use.

Goto Setup->Develop->Apex Classes

Create a class with following code

global class myHandler implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
Messaging.InboundEnvelope envelope) {

Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
return result;
}
}

Now lets create a email service.

Setup->Develop->email services->

click on the button New Email service

To know about the various fields refer the docs here

Make sure you select the apex class you created earlier. After the email service is created you should scroll down to the bottom of the screen to find the email address to which the emails need to be sent.

Now open up the class which you had selected while creating the email service. Here is the code i wrote.

global class ProcessCaseEmail implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
    String myPlainText= '';
    myPlainText = email.plainTextBody;
    System.debug('Plain text+++++++++++' + myPlainText );
    List<String> parts = myPlainText.split('\n\n');

    List<String> columns;
    for(integer i=0;i<parts.size();i++)
    {

    System.debug('Parts+++++     ['+i+']   '+parts[i] );
    system.debug('Length of the parts ['+i+']  '+parts[i].length());
    if (parts[i].length()<9)
    {

    }
    else
    {
     System.debug('Parts+++++     ['+i+']   '+parts[i] );
     columns=parts[i].split('\\|'); 

     System.debug('columns size++++++++++++  '+columns.size());
     string acc='';
     acc=columns[2].trim();
     acc=acc.replaceAll('[^\\d\\w]','');
         System.debug('++++++acc after removing non print chars'+acc);

     List<Account> ac = [select id, name from account where accountid__c=:acc];
     System.debug('acc +++++++++++'+ac);

     for(integer k=0;k<ac.size();k++)
     {

     System.debug('+++++++++++++++matched account++++++++++++++++++');
     case c = new case();
     c.incident__c=columns[0];
     c.subject=columns[1];
     c.account__c=columns[2];
     c.created__c=columns[3];
     c.events__c=columns[4];
     c.type__c=columns[5];
     c.begin_date__c=columns[6];
     c.status__c=columns[7];
     c.notification_status__c=columns[8];
     c.AccountID=ac[k].id;
     insert c;

     }
    }
   // }

    }
         return result;
    }

  }

Lets break the code down

To read the content of the email we are using the following code

myPlainText = email.plainTextBody;

Here is where we store the body of the email into a string
Another very important thing is that we need to give a system.debug to get an idea of how the email body is received. In some instance the rows are divided by two lines or one line. Depending on how your email is sent we can break the string to rows by using the code In my case it was a two lines.

 List parts = myPlainText.split('\n\n');

We have a list with all the records.
Now that we have all the records lets break the rows into columns I have the columns seperated by | symbol
So first lets loop through the all the records one by one and break each row into columns and then create a case for that record.

One other challenge i faced was when i was breaking the string into rows, there was a possibility that were blank rows as the email would have had multiple blank rows.
I have taken care of it using the if statement

  if (parts[i].length()<9)

I use 9 coz the no of columns in record is 8. So if the length is less than 9 that would mean a blank record. This may not be the right method. You could break the row into columns and count the no of columns if its less than no of column for the record then its a invalid record and ignore the record.
Here is how you break the records into columns

 columns=parts[i].split('\\|'); 

There is one other thing i am doing i am looking for a account which is related by a custom field. So from one of the column i search for the account which matches the custom field and give the account id to the case so that the new case is related to the account.

Since we are taking the values from email and breaking the records into columns based on the pipe symbol. There value of the column is can contain blank characters and non printing characters which would mean you would not find a matching record in account.

 List ac = [select id, name from account where accountid__c=:acc];

So make sure you trim and remove all non printing charaters.

 acc=acc.replaceAll('[^\\d\\w]','');

I know in my case the column just had only numbers and alphabets so i used the above regex you can change the regex according to your requirements.

This really is my first detailed post so if you think there is something i can improve upon do drop a comment.

I currently work for CM-Focus

Advertisements

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 )

w

Connecting to %s

%d bloggers like this: