Search code examples
c#asp.netmandrill

Mandrill Mailchimp how to embed an image in email body


I want to embed an image in email footer. I have used "LinkedResources" to do this with .NET mail client previously. (mailObject.AlternateViews.Add(footerImageLinkedResource);)

But with Mandrill api does not have an Alternate view.

Sample code I tried is as follows with Mandrill,

MailChimp.Types.Mandrill.Messages.Message message = new MailChimp.Types.Mandrill.Messages.Message();    
Stream ms = new FileStream(@"C:\sam.jpg", FileMode.Open);
string src = ImageFormatter.GetImageURL(ms);
ms.Close();
message.Html = body + "<p><a href=\"" + websiteUrl + "\"><img alt=\"" + websiteUrl + "\" src=\"" + src + "\" /></a></p>";

How can I achieve this task? (If the src is given as a URL it works fine, but I want to embed the image)


Solution

  • You can use the images API parameter as per this page:

    http://help.mandrill.com/entries/25252978-Tips-for-using-images-in-Mandrill-emails

    You need to provide the image name, base64-encoded image and the mime-type of the image, then refer to the image by its name in your email's HTML. It might look like this using the .NET Mandrill API wrapper (https://github.com/shawnmclean/Mandrill-dotnet) (untested):

    List<Mandrill.image> images = new List<Mandrill.image>();
    Mandrill.image img = new Mandrill.image();
    byte[] fileData = File.ReadAllBytes("C:\sam.jpg")
    img.content = Convert.ToBase64String(fileData)
    img.type = "image/jpeg"
    img.name = "image_name"
    images.Add(Image)
    Email.images = images //(where Email is a Mandrill.EmailMessage)
    

    And then in your email you would have code like this:

    <img src="cid:image_name">
    

    Which will show that image by ID that you sent with the email.