How to send email messages with embedded images

May 01, 2013 by Anuraj

.Net ASP.Net CodeProject Windows Forms

While creating email messages with HTML content, normally the images are displayed with IMG tag, where the SRC attribute pointing to an image, which is hosted in the web server. Most email clients will not display the images, which is downloading from the web. Instead of pointing to web URL, you can embed image in the mail message with the help of LinkedResource and AlternateView classes.

Here is the snippet, which embed an image to the email. The convention to access linked resource is cid:name of the linked resource, which is the value of IMG tag SRC attribute.

var logo = new LinkedResource(@"C:\logo.jpg");
logo.ContentId = Guid.NewGuid().ToString();
var body = 
    string.Format(@"<html><body>

# Image

![]()</body></html>", 
    logo.ContentId);
var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
view.LinkedResources.Add(logo);
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body,
    IsBodyHtml = true
})
{
    message.AlternateViews.Add(view);
    smtp.Send(message);
}

Note: This method will increase the size of the email, as the images are embedded.

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub