12 Jun 2012

Sending email with inline images in ASP.NET MVC

To use inline images in your email, your mail should use HTML format and refer to the images using the collection of Linked Resources, like so.

using (var client = new SmtpClient())
    MailMessage newMail = new MailMessage();
    newMail.To.Add(new MailAddress("you@your.address"));
    newMail.Subject = "Test Subject";
    newMail.IsBodyHtml = true;

    var inlineLogo = new LinkedResource(Server.MapPath("~/Path/To/YourImage.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");


The benefit of this approach over the use of the Attachments collection is that the linked images do not appear in the mail client's list of attachments for the mail.

No comments:

Post a Comment

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!