Saturday, 9 August 2014

Handling Inline Images in Salesforce Inbound Email

One of the Salesforce powerful feature is Inbound Email Services. Using this, you can send an email to Salesforce and process the email body as you want. Inbound email handler class allows you to access email’s plain text body as well as html body.

One issue that I came across was, none of the existing method can handle your inbound email’s inline images. I searched community a lot and realized that, too many people had the same issue but they never find any solution, so I thought to pick it from there.

Issue:
You want to write email’s HTML body in a Rich Text area field and your email has inline images. Now, when you send this, inbound email will lost those images references and your body will say “Inline Image XXXXX”.

More Detail:
I have created an email service in my org. It only listens inbound email and put the email’s HTML body in a rich text area field on lead.

global class POCEmailHandler implements Messaging.InboundEmailHandler {
    
    //Method to process email 
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        
        //Create a New Lead record
        Lead lead = new Lead();
        lead.LastName = 'Inbound Lead';
        lead.Email = email.fromAddress;
        lead.Company = 'N/A';
        lead.HTML_Body__c = email.htmlBody;
        
        //Insert record
        insert lead;
    }
}


Now I sent below email to this email service. Inbound handler class processed it and a new lead was created in system.



This lead was created in system. Notice the HTML Body field.












Inline image didn’t came in the HTML body.

Reason:
Salesforce process inline images as binary attachments. When you send an email having inline images, it doesn’t come as a part of body, but it comes as binary attachment. From here, you will have to put your own logic to place the inline images back in HTML Body.

Resolution:

1.       Process binary attachments and see, which attachment came as a part on inline image. Create an attachment record for each image. Below code is to create a map with the inline image name and its related attachment record.


//Create a list of attachments
        Map< String, Attachment > mapAttachments = new Map< String, Attachment >(); 
        
        //Attachments
        for(Messaging.InboundEmail.BinaryAttachment bA : email.binaryAttachments) {
            System.debug(bA);
            for(integer i = 0; i < bA.headers.size(); i++) {
                
                //Header Value
                String headerValue = bA.headers[i].value;
                if(headerValue.startsWith('ii') || headerValue.startsWith('< image')) {
                    headerValue = headerValue.replaceAll('<', '').replaceAll('>', '');
                    mapAttachments.put(headerValue, new Attachment(Name = bA.fileName, body = bA.body, 
                                                    ParentId = lead.Id, ContentType = bA.mimeTypeSubType));
                }
            }
        }



2.       Now process HTML body content and get all the places where actual Inline Image was replaced with blank space and update these instances with the attachment link.
//Process inline images and update the HTML Body
        for(String headerValue : mapAttachments.keySet()) {
    
            //Reference Link
            String refLink = '/servlet/servlet.FileDownload?file=' + mapAttachments.get(headerValue).Id;
            lead.HTML_Body__c = lead.HTML_Body__c.replaceAll('cid:' + headerValue, refLink);
        }
        update lead;
 


Updated code will look like this.
global class POCEmailHandler implements Messaging.InboundEmailHandler {
    
    
global class POCEmailHandler implements Messaging.InboundEmailHandler {
    
    //Method to process email 
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        
        //Create a New Lead record
        Lead lead = new Lead();
        lead.LastName = 'Inbound Lead';
        lead.Email = email.fromAddress;
        lead.Company = 'N/A';
        lead.HTML_Body__c = email.htmlBody;
        
        //Insert record
        insert lead;
        
        //Create a list of attachments
        Map< String, Attachment > mapAttachments = new Map< String, Attachment >(); 
        
        //Attachments
        for(Messaging.InboundEmail.BinaryAttachment bA : email.binaryAttachments) {
            System.debug(bA);
            for(integer i = 0; i < bA.headers.size(); i++) {
                
                //Header Value
                String headerValue = bA.headers[i].value;
                if(headerValue.startsWith('ii') || headerValue.startsWith('< image')) {
                    headerValue = headerValue.replaceAll('<', '').replaceAll('>', '');
                    mapAttachments.put(headerValue, new Attachment(Name = bA.fileName, body = bA.body, 
                                                    ParentId = lead.Id, ContentType = bA.mimeTypeSubType));
                }
            }
        }
        
        //Insert
        insert mapAttachments.values();
        
        //Process inline images and update the HTML Body
        for(String headerValue : mapAttachments.keySet()) {
    
            //Reference Link
            String refLink = '/servlet/servlet.FileDownload?file=' + mapAttachments.get(headerValue).Id;
            lead.HTML_Body__c = lead.HTML_Body__c.replaceAll('cid:' + headerValue, refLink);
        }
        update lead;
        
        return result;
    }
}




Now send the same email to Salesforce email address and see the result.













Don't  miss DF-14. See you there.
http://bit.ly/df14infblog
Join us in the Developer Zone at Dreamforce 2014 | Training, Talks & MoreSalesforce
Join Salesforce Developers from around the world in the Developer Zone at Dreamforce 2014. Learn new skills through interactive sessions and hands-on training. Immerse yourself in the tools and knowledge you need to build better, faster, and deliver more. For a limited time developers can register for Dreamforce at a special rate of $899.

25 comments:

  1. Salesforce Admin Online Training,
    Salesforce CRM Online Training,
    Salesforce Developer Online Training,
    ONLINE TRAINING – IT SUPPORT – CORPORATE TRAINING
    The 21st Century Software Solutions of India offers one of the Largest conglomerations of Software Training, IT Support, Corporate Training institute in India - +919000444287 - +917386622889 - Visakhapatnam,Hyderabad
    Salesforce Admin Online Training, Salesforce Admin Training, Salesforce Admin, Salesforce Admin Online Training| Salesforce Admin Training| Salesforce Admin|
    Salesforce CRM Online Training, Salesforce CRM Training, Salesforce CRM, Salesforce CRM Online Training| Salesforce CRM Training| Salesforce CRM|
    Salesforce Developer Online Training, Salesforce Developer Training, Salesforce Developer, Salesforce Developer Online Training| Salesforce Developer Training| Salesforce Developer|
    Salesforce Admin Online Training, Salesforce Admin Training, Salesforce Admin, Salesforce Admin Online Training| Salesforce Admin Training| Salesforce Admin|
    Salesforce CRM Online Training, Salesforce CRM Training, Salesforce CRM, Salesforce CRM Online Training| Salesforce CRM Training| Salesforce CRM|
    Salesforce Developer Online Training, Salesforce Developer Training, Salesforce Developer, Salesforce Developer Online Training| Salesforce Developer Training| Salesforce Developer|
    Visit: http://www.21cssindia.com/courses.html

    ReplyDelete
  2. I am only able to get this to work when sending an email from Gmail. If I use outlook, it strips the message of all images and attachments. Do you know how to make it work with all email clients?

    ReplyDelete
    Replies
    1. I had tested this with outlook as well and it was working that time. I will recheck whenever I get time.

      Delete
  3. Thanks for sharing informative article on Salesforce technology. Your article helped me a lot to understand the career prospects in cloud computing technology. Salesforce Training in Chennai

    ReplyDelete
  4. Nice article.......... The consequent program is also designed in such a way so that it will help in building applications and customize multi-user cloud applications a few clicks few clickety, it will help in automating your business processes.For more details salesforce training in hyderabad

    ReplyDelete
  5. Thanks for sharing informative article on cloud computing technology. Your article helped me a lot in understand the future of cloud technology. Having strong expertise in leading cloud based CRM like Salesforce will ensure better career prospects for aspiring professionals. Salesforce Training in Chennai | Hadoop Training in Chennai

    ReplyDelete
  6. interesting information. This is just the kind of information that i had been looking for, i'm already your rss reader now and i would regularly watch out for the new posts,Thanks a million once again, Regards,servicenow training in hyderabad ,splunk training in hyderabad

    ReplyDelete
  7. Thanks for sharing. Its really good. But what i noticed is if i send an email to create a case, in the case feed view the inline image does not appear. But in the email itself we can see in the html version.

    In case feed it shows as [Image is no longer available] can you please help?

    Thanks
    -Pavan

    ReplyDelete
    Replies
    1. Hi Pavan.
      We experience the same issue with Case Feed - images appear as [Image is no longer available].
      Did you manage to solve this?

      Thank you,
      Ido.

      Delete
    2. Hi, We are having the same issue, did anyone find a solution for this?

      Delete
  8. I have the same problem!

    ReplyDelete
  9. we are offering best splunk online training with job support and high quality training facilities and well expert faculty . to Register you free demo please visit ,splunk training in hyderabad

    ReplyDelete
  10. Much nice information you had told here. Within this we can manage the inline images. Now its cleared thank ou for sharing this information through this.

    SEO Training in Chennai

    ReplyDelete
  11. Really an awesome post. I wondered by reading this blog post. Thanks a lot for posting this unique post which you have shared with us. Keep on posting like this exclusive post with us.

    Seo Company in Chennai

    ReplyDelete
  12. Thank you for sharing such a nice and interesting blog with us. i have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle. please keep on updates. hope it might be much useful for us. keep on updating...
    Android training in chennai

    ReplyDelete
  13. Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    iOS Training in Chennai

    ReplyDelete
  14. this is really too useful and have more ideas from yours. keep sharing many techniques. eagerly waiting for your new blog and useful information. keep doing more.
    SAT Coaching Chennai

    ReplyDelete
  15. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
    SEO Company in India

    ReplyDelete

  16. Wonderful blog.. Thanks for sharing informative Post. Its very useful to me.

    Installment loans
    Payday loans
    Title loans

    ReplyDelete
  17. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

    Android App Development Company

    ReplyDelete
  18. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
    iOS App Development Company
    iOS App Development Company

    ReplyDelete
  19. Its fantatic explaintion lot of information gather it...nice article....
    seo company in Chennai

    ReplyDelete
  20. Its fantatic explaintion lot of information gather it...nice article....
    seo company in Chennai

    ReplyDelete