How to Embed Images in the Body of an Email Message

Another very simple C# sample based on a mail merge application I have been working on. This time I would like to show you how to use the System.Net.Mail facilities to programmatically embed images in the html body of an email.

public static void SendMessage(string server,
    string from, string to, string cc, string bcc,
    string subject, string body, List<string> attachments,
    string[] embeddedFiles)
{
    MailMessage message = new MailMessage(from, to);
    message.Subject = subject;
    string[] ccArray = cc.Split(';');
    if (ccArray.Length > 0)
    {
        foreach (string address in ccArray)
        {
            if (address.Length > 0)
            {
                message.CC.Add(new MailAddress(address));
            }
        }
    }
    string[] bccArray = bcc.Split(';');
    if (bccArray.Length > 0)
    {
        foreach (string address in bccArray)
        {
            if (address.Length > 0)
            {
                message.Bcc.Add(new MailAddress(address));
            }
        }
    }
    message.IsBodyHtml = true;
    if (null != embeddedFiles && embeddedFiles.Length > 0)
    {
        foreach (string filePath in embeddedFiles)
        {
            string fileName = Path.GetFileName(filePath);
            body = body.Replace(fileName, "cid:" + fileName);
        }
        AlternateView view = AlternateView.CreateAlternateViewFromString(body,
            null,MediaTypeNames.Text.Html);
        foreach (string filePath in embeddedFiles) {
            LinkedResource res = new LinkedResource(filePath);
            res.ContentId = Path.GetFileName(filePath);
            view.LinkedResources.Add(res);
        }
        message.AlternateViews.Add(view);
    } else {
        message.Body = body;
    }
    foreach (string file in attachments) {
        Attachment data = new Attachment(file);
        message.Attachments.Add(data);
    }
    SmtpClient client = new SmtpClient(server);
    client.Credentials = CredentialCache.DefaultNetworkCredentials;
    client.Send(message);
}

The trick here consists in creating an AlternateView instance for the body of the email and adding the images to this view via LinkedResource instances. Also, note how the paths to the original images inside de html body are replaced with unique identifiers that map to their embedded siblings.

More details on this approach can be found here.

About Jorge

Jorge is the author of Building a Sencha Touch Application, How to Build a jQuery Mobile Application, and the Ext JS 3.0 Cookbook. He runs a software development and developer education shop that focuses on mobile, web and desktop technologies.
If you'd like to work with Jorge, contact him at ramonj[AT]miamicoder.com.

Speak Your Mind

*