C# sending mails with images inline using SmtpClient

KdgDev picture KdgDev · Jul 31, 2009 · Viewed 60.1k times · Source

SmtpClient() allows you to add attachments to your mails, but what if you wanna make an image appear when the mail opens, instead of attaching it?

As I remember, it can be done with about 4 lines of code, but I don't remember how and I can't find it on the MSDN site.

EDIT: I'm not using a website or anything, not even an IP address. The image(s) are located on a harddrive. When sent, they should be part of the mail. So, I guess I might wanna use an tag... but I'm not too sure, since my computer isn't broadcasting.

Answer

James McCormack picture James McCormack · Jun 12, 2012

One solution that is often mentioned is to add the image as an Attachment to the mail, and then reference it in the HTML mailbody using a cid: reference.

However if you use the LinkedResources collection instead, the inline images will still appear just fine, but don't show as additional attachments to the mail. That's what we want to happen, so that's what I do here:

using (var client = new SmtpClient())
{
    MailMessage newMail = new MailMessage();
    newMail.To.Add(new MailAddress("[email protected]"));
    newMail.Subject = "Test Subject";
    newMail.IsBodyHtml = true;

    var inlineLogo = new LinkedResource(Server.MapPath("~/Path/To/YourImage.png"), "image/png");
    inlineLogo.ContentId = Guid.NewGuid().ToString();

    string body = string.Format(@"
            <p>Lorum Ipsum Blah Blah</p>
            <img src=""cid:{0}"" />
            <p>Lorum Ipsum Blah Blah</p>
        ", inlineLogo.ContentId);

    var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
    view.LinkedResources.Add(inlineLogo);
    newMail.AlternateViews.Add(view);

    client.Send(newMail);
}

NOTE: This solution adds an AlternateView to your MailMessage of type text/html. For completeness, you should also add an AlternateView of type text/plain, containing a plain text version of the email for non-HTML mail clients.