Thursday, February 6, 2014

Email services

Welcome guys to this blog.
This time we are going to discuss on the Email services in the salesforce. Salesforce provides the facility to create the new record using the Email service.  We will see the example of creating case and case comment by using the Email service. To implement this functionality we need three thing as Apex Controller, Enabled Email Service, Apex Trigger on CaseComment object in any salesforce org. So let's start.
To create the email service we need a apex controller same as the the following.

**********************Controller************************************

global class emails implements Messaging.InboundEmailHandler{
      global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,     Messaging.InboundEnvelope envelope) {
          Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
          string subject1 = email.subject;
          string body = email.plainTextBody;
          Attachment attachment = new Attachment();
          string sender = email.fromAddress;
          string st = body;
          string cname = email.fromName;
          string sub;
          List<contact> contacts;
          contacts = new List<contact>();
          List<case> cases;
          cases = new List<case>();
          contacts =[select id, Email,Account.ID, Name from contact where Email =: sender limit 1];
          if(subject1.contains('Re:')){
              integer i = subject1.length();
              sub = subject1.substring(4,i);
          }else{
              sub = subject1;
          }
         if(contacts.size()>0){       
                for(contact con : contacts){
                      if(con.id != null)
                      {
                         cases = [select id, CaseNumber from case];
                         for(case c : cases)
                         {
                             if(c.CaseNumber.contains(sub))
                             {
                                 c.subject=subject1;
                                 c.caseIdentifier__c = false;
                                 c.Description=body;
                                 c.Status='Working';
                                 c.Origin='Email';
                                 c.Severity__c='<-----None--->';
                                 c.Reported_at__c=c.CreatedDate;
                                 update c;
                               
                                    CaseComment cc = new CaseComment(ParentId=c.Id,CommentBody=st,IsPublished=true);
                                    insert cc;
                          
                                    if(email.TextAttachments !=null){
                                       for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {  
                                            attachment.Name = tAttachment.fileName;  
                                            attachment.Body = Blob.valueOf(tAttachment.body);  
                                            attachment.ParentId = c.Id;  
                                            insert attachment;  
                                       }
                                    }  
                                   if(email.BinaryAttachments !=null){
                                        for (Messaging.Inboundemail.BinaryAttachment ttAttachment : email.BinaryAttachments) {  
                                            attachment.Name = ttAttachment.fileName;  
                                            attachment.Body = ttAttachment.body;  
                                            attachment.ParentId = c.Id;  
                                            insert attachment;  
                                        }  
                                   }
                                   return result;
                           }
                          }
                    if(con.Email == sender)
                    {
                        case cs = new case(contactID=con.ID,description=body,origin='email',Severity__c='None',status='new');
                        insert cs;
                        CaseComment cc1 = new CaseComment(ParentId=cs.Id,CommentBody=st.abbreviate(4000),IsPublished=true);
                        insert cc1;
                         
                    }
          }
        
        }
        }
        else
        {
              contact c;
              c = new contact();
              c.LastName =cname;
              c.subjects__C = 'java';
              c.Email=sender;
              insert c;
              
              case cs1 = new case(contactID=c.ID,description=body,origin='email',status='new');
              insert cs1;
               
        }
          return result;
      }
      
  }

********************************Controller************************************

After saving that controller we need to make the Email Service in the salesforce. To create the email service in the salesforce you have to move as setup -> App setUp -> develop -> Email service . Just click on the New Service . When you are going to create the email service  you will see that there is an option to add the
Apex class. In that option we will add our above class. When you finished the process of creating the Email Service , you will get an address. Thar address should be added in gmail account as Forward Message which gmail account is being in the Salesforce org.

When you send email to this address a new Case and a new Contact will be created in the salesforce org. That contact will be associated that case.
This is the first step. In next step we will see that when we add a comment in Case comment of the salesforce, then an email will be sent to the contact who is associated with this case. That contact will receive an email . If that contact send any reply to that email , then new comment will be created in same case in the salesforce and the process is so on.
To implement the second step we need to write a trigger on the CaseComment object in salesforce.

***************************trigger*********************************************

 trigger casetest on CaseComment (after insert) {
    set<Id> caseId = new set<Id>();
    set<Id> conId = new set<Id>();
    set<Id> conId1 = new set<Id>();
    list<CaseComment> lst = new list <CaseComment>();
    Id contId;
    string caseNo;
    boolean flag;
    string comment;
    for(CaseComment cs : trigger.new){
        caseId.add(cs.Id);
       
    }
     if(CaseId.size() > 0){
    
    lst = [select id,commentbody,parentid from CaseComment where id in :caseId];
    }
    
    if(lst.size()>0){
    
    for(CaseComment css: lst){
    
    conId1.add(css.parentid);
    
     comment = css.commentBody;
    
    }
    }
    List<case> cse = new List<case>();
    if(conId1.size() > 0){
        List<case> cases = new List<case>();
        cases = [select id, casenumber, contactId, caseIdentifier__c,description         from case where id in : conId1];
        if(cases.size() > 0){
            for(case cs : cases){
            system.debug('ajit'+ comment +'ajit1'+cs.description);
            if(cs.description==null){
            
            caseNo = cs.caseNumber;
                contId = cs.contactId;
               flag = true;
            
            
            }
            else{
              if(comment.equals(cs.description)==false ){
                caseNo = cs.caseNumber;
                contId = cs.contactId;
               flag = true;

               }  
               }
            }
            
        }
       
    } 
    if(flag == true){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setSubject(caseNo);  
        mail.setTargetObjectId(contId);
        mail.setreplyTo('my_email_services@2hpulp0pv93g3rbe2ng8dzw0ocs0wzyupuemgncw5cnhjoiffg.9-gjk7eaa.9.apex.salesforce.com');
        mail.setSaveAsActivity(false);
        mail.setHtmlBody(comment);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
     }   
}
So in above blog we saw that how to create a new case and casecomment in salesforce using Email service.
If you any doubt or issue then let me know.

Monday, February 3, 2014

Email Services via Apex code

Today i am going to introduce the the email services via Apex code in salesforce. Some time we need to send an email via vf page . That time we need of Cc , Bcc. Here i will post the code what will be used to create  the email service using Apex code.
Here  i am adding on more thing to send the in email that List of Account. Account is just for an example. In the same process we can send also the another object's records.


*************************VF page****************************************

<apex:page showHeader="false" sidebar="false" standardStylesheets="false" controller="EmailSendController">
   <apex:form id="frm">
          <apex:actionFunction name="addmeAccount" action="{!sendAccount}" status="status">
            <apex:param name="index" value="" assignTo="{!Index}"/>
          </apex:actionFunction>
          <apex:actionStatus id="status">
                <apex:facet name="start">
                <div style="width: 500px;">
                <img src="/img/loading24.gif" style="vertical-align:middle;margin-left:50px;"/>
                <span style="margin-left:10px; font-size: 12px; font-weight: bold; color: #000000;">Please wait...</span>
                </div>
                </apex:facet>
          </apex:actionStatus>
          <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="0">
             <tr bgcolor="#222222">
                 <td  width="90%" colspan="4">
                     <b><font size="3" color="White">New Message</font></b>
                 </td>
                 <td align="right" colspan="4">
                     <apex:image value="{!$Resource.Minusimage}" width="15px" height="15px" title="Minimize"/>
                 </td>
                 <td align="right" colspan="4">
                     <apex:image value="{!$Resource.MultiplyImage}" width="15px" height="15px" title="Close"/>
                 </td>
             </tr>
          </table><br/>
          <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="2">
             <tr>
                 <td width="14%">
                     <b><font size="3" color="#2F4F4F">To</font></b>
                 </td>
                 <td width="90%">
                     <apex:inputText size="80" value="{!to}"/>
                 </td>  
                 <td width="14%">
                     <apex:commandLink value="Cc" action="{!mailcc}"/>
                 </td>
                 <td width="5%">
                     <apex:commandLink value="Bcc" action="{!mailbcc}"/>
                 </td>
             </tr>
             <apex:pageBlock rendered="{!cc}" id="mecc">
                 <tr>
                     <td width="5%" rowspan="4">
                         <b><font size="3" color="#2F4F4F">Cc</font></b>
                     </td>
                     <td width="90%" rowspan="4">
                         <apex:inputText size="80" value="{!addcc}"/>
                     </td>
                 </tr>
             </apex:pageBlock>
           </table>
           <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="2">
              <apex:pageBlock rendered="{!bcc}">
                 <tr>
                     <td width="9%" rowspan="4">
                         <b><font size="3" color="#2F4F4F">Bcc</font></b>
                     </td>
                     <td width="90%" rowspan="4">
                         <apex:inputText size="80" value="{!addBcc}"/>
                     </td>
                 </tr>
             </apex:pageBlock>  
         </table>
         <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="2">
             <tr>
                 <td width="9%">
                         <b><font size="3" color="#2F4F4F">Subject</font></b>
                 </td>
                 <td width="90%" >
                         <apex:inputText size="80" value="{!sub}"/>
                 </td>
             </tr>
             <tr>
                 <td colspan="2">
                     <apex:inputTextarea richText="true" value="{!body}"/>
                 </td>
             </tr>
         </table>
         <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="2">
             <tr>
                 <td>
                     <apex:commandButton image="{!$Resource.SendButton}" action="{!mail}"/>
                 </td>
                  <td>
                      <b><apex:commandlink value="+" style="text-decoration: none;" action="{!hello}"/></b>
                 </td>
                 <apex:pageBlock id="acol" rendered="{!acol}">
                     <td>
                          <b><apex:commandlink value="Account" style="text-decoration: none;" action="{!addAccount}"/></b>
                     </td>
                     <td>
                          <b><apex:commandlink value="Contact" style="text-decoration: none;"/></b>
                     </td>
                     <td>
                          <b><apex:commandlink value="Opportunity" style="text-decoration: none;"/></b>
                     </td>
                     <td>
                          <b><apex:commandlink value="Lead" style="text-decoration: none;"/></b>
                     </td>
                 </apex:pageBlock>
             </tr>
         </table><br/>
         <table border="0"  width="40%" align="center" cellspacing="0" cellpadding="2">
             <tr>
                 <td align = "center">
                     <apex:commandButton value="Add to mail" rendered="{!accbtn}" action="{!sendAccount}"/>
                 </td>
             </tr>
             <tr>
                 <td width="100%">
                     <apex:pageBlock >
                         <apex:pageblockTable value="{!nc}" var="nsc" width="100%">
                             <apex:column >
                                 <apex:inputCheckbox  value="{!nsc.acctrue}"/>
                             </apex:column>
                             <apex:column >
                                 {!nsc.sr}
                             </apex:column>  
                             <apex:column value="{!nsc.acct.name}"/>
                             <apex:column value="{!nsc.acct.accountnumber}"/>
                             <apex:column value="{!nsc.acct.phone}"/>
                         </apex:pageblockTable>
                     </apex:pageBlock>
                 </td>
             </tr>
         </table>
     </apex:form>
</apex:page>



*****************************Controller***********************************

Public Class EmailSendController{
    public boolean cc {get; set;}
    public boolean bcc {get; set;}
    public boolean acol {get; set;}
    public string to {get; set;}
    public string sub {get; set;}
    public string body {get; set;}
    public string addBcc {get; set;}
    public string addcc {get; set;}
    public List<Account> acc {get; set;}
    public List<NestedClass> nc {get; set;}
    public integer index {get; set;}
    public boolean accbtn {get; set;}
    public List<Account> selectedAcc {get; set;}
    public String s {get; set;}
    public List<String> s1 {get; set;}
    public EmailSendController(){
        cc = false;
        bcc = false;
        acol = false;
        accbtn = false;
        s1 = new List<String>();
     
    }
    public pagereference mailcc(){
        if(cc == false){
            cc = true;
        }else{
            cc = false;
        }
        return null;
    }
    public void mailbcc(){
        if(bcc == false){
            bcc = true;
        }else{
            bcc = false;
        }
    }
    public pagereference hello(){
        if(acol == false){
            acol = true;
        }else{
            acol = false;
        }
        return null;
    }
    public pagereference addAccount(){
       acc = new list<Account>();
       nc = new List<NestedClass>();
       accbtn = true;
       acc = [select id, name , AccountNumber, phone from account];
       integer i = 1;
       for(Account ac : acc){
           nestedClass nsc = new NestedClass();
           nsc.sr = i++;
           nsc.acct = ac;
           nc.add(nsc);
       }
       return null;
    }
    public pageReference sendAccount(){
        selectedAcc = new List<Account>();
        if(nc.size() > 0){
            account selectedAccount = new account();
            for(NestedClass ac : nc){
               if(ac.acctrue == true){
                  selectedAcc.add(ac.acct);
               }
            }
        }
       for(Account acc : selectedAcc){
     
            s = '<Html>' ;
                      s += '<head>' ;
                      s += '</head>' ;
                      s += '<body>' ;
                          s += '<table border="0" bgcolor="#E6E6FA">';
                              s += '<tr>';
                                  s += '<th style="color : red;">';
                                      s += 'Account Name';
                                  s += '</th>';
                                  s += '<th style="color : red;">';
                                      s += 'Account Number';
                                  s += '</th>';
                                  s += '<th style="color : red;">';
                                      s += 'Phone';
                                  s += '</th>';
                              s += '</tr>';
                              s += '<tr>';
                                  s += '<td style="color : blue;">';
                                      s += string.valueOf(acc.Name);
                                  s += '</td>';
                                  s += '<td style="color : blue;">';
                                      s += string.valueOf(acc.AccountNumber);
                                  s += '</td>';
                                  s += '<td style="color : blue;">';
                                      s += string.valueOf(acc.phone);
                                  s += '</td>';
                              s += '</tr>';
                          s += '</table>';
                      s += '<body>' ;
                  s += '</html>' ;
                  s1.add(s);
       }
        return null;
    }
    public pagereference mail(){
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String addresses;
        addresses = to;
        String[] toAddresses = addresses.split(',', 0);
        email.setSubject(sub);
        if(addBcc != null){
            String[] toBccAddresses = addBcc.split(',', 0);
            if(toBccAddresses.size() > 0 && toBccAddresses != null){
                email.setBccAddresses(toBccAddresses);
            }
        }
        if(addcc != null){    
            String[] toccAddresses = addcc.split(',', 0);
            if(toccAddresses.size() > 0 && toccAddresses != null ){
                email.setccAddresses(toccAddresses);
            }
        }  
        email.setReplyTo('excellencegaur@gmail.com');
        email.setHTMLBody(body+ '' +s1);
        email.setToAddresses(toAddresses);
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>{email};
        Messaging.SendEmailResult [] r = Messaging.sendEmail(emails);
        return null;
    }
    public class NestedClass{
        public account acct {get; set;}
        public integer sr {get; set;}
        public boolean acctrue {get; set;}
    }
}

If you have any confusion related to this post , then let me know.