Thursday, November 7, 2013

Embedding images in email, Dynamics CRM 2011 - Part 1

Today I am going to show you a way you can send emails with embedded images in CRM 2011 /2013 and for that matter Crm 4.0.
This is nothing new, you might say... images can be added by just copying the image which is available on a public URL and pasting it in the CRM email form and the image will appear.
If you thought this then you are definitely correct. However what if you had a requirement where the images could not be put on a public URL ( or CDN), how would you allow images then.
Well as a smart CRM developer you would say, mail merge? or have the email contain a document as attachment with the image, etc. etc. There are many ways it can be done.

Okay enough of the daddy talk, let me tell you another way which many of you probably already knew. Lets revisit emails and more importantly the MIME content disposition specification which details how email attachments are constructed and which governs how the email clients deal with your email. Essentially what this will tell you is that you can embed images inside the email if you create the attachment as "inline" and reference it is your email body.
To achieve in CRM, we will somehow need to interact with our outgoing email just before it is submitted to the SMTP server for delivery. We will have to convert our images to "inline" attachments and reference them in the email body so that on the other side they come out as email which contain images.

Now the fun part, To implement this we won't be doing adding anything extra to our CRM email form, we will still put the image in the email body as described above - copy -paste, but this time our image is no longer required to be on the a public URL or CDN, it can remain in our internal network. Our code will grab it form our internal network, convert it into a MIME inline attachment and reference it in the email body.

But where and how will we do this you ask? Well the plain old router, yes its the same router that we are all too used to, this time we will be extending the SMTP provider, specifically we will be creating a class that implements  SmtpPollingSendEmailProvider. We have to do this inorder to construct the email ourselves, replace the img tag with the equivalent mime attachment reference and also convert the image to an inline mime attachment.
We will override the Run method, grab the email that needs to be sent and use System.Net.Mail to construct an email, along with the attachment which we will read from the <img src=url>  and then send it through our configured smtp server.

That's it voila! email with embedded image.
In the next part I will share the code along with steps to extend the router to achieve this.

Happy CRMing.

Disclaimer: This method of embedding images is probably not the best performing option, your first choice should always be images that are on a CDN.


2 comments: