.NET life

HUGON Jérôme
Microsoft Certified Technology Specialist Microsoft Certified Application Developer Microsoft Certified Professional

Send an email with pictures included

.NET

Category .NET  | Publication Date : 8/18/2009

Create an object LinkedResource. The LinkedResource will contain the data binary image. These binary data are encoded in the e-mail, and sent into the object MailMessage.

Donate to LinkedResource a unique name, also known as a Content-Id.

Create an AlternateView HTML.

In the HTML text, you must use the tag <img>. For the src attribute, you must insert the identifier of the LinkedResource using the syntax <img src="cid:CONTENT-ID">.

The mail client reads the image without making a HTTP request.

C#.NET:

static void EmbedImages()
{
    MailMessage mail = new MailMessage();
    mail.To.Add("you@domain.com");
    mail.Subject = "Email with embedded image";

    AlternateView plainView = AlternateView.CreateAlternateViewFromString("Email text for mail clients that do not support HTML emails", null, "text/plain");

    AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<img src=cid:logo>", null, "text/html");

    LinkedResource logo = new LinkedResource("c:\\temp\\logo.gif");
    logo.ContentId = "logo";

    htmlView.LinkedResources.Add(logo);

    mail.AlternateViews.Add(plainView);
    mail.AlternateViews.Add(htmlView);

    SmtpClient smtp = new SmtpClient();
    smtp.Send(mail);
}

VB.NET:

Sub EmbedImages()
    Dim mail As New MailMessage()
    mail.To.Add("you@domain.com")
    mail.Subject = "Email with embedded image"

    Dim plainView As AlternateView = AlternateView.CreateAlternateViewFromString("Email text for mail clients that do not support HTML emails", Nothing, "text/plain")

    Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("<img src=cid:logo>", Nothing, "text/html")

    Dim logo As New LinkedResource("c:\temp\logo.gif")
    logo.ContentId = "logo"

    htmlView.LinkedResources.Add(logo)

    mail.AlternateViews.Add(plainView)
    mail.AlternateViews.Add(htmlView)

    Dim smtp As New SmtpClient()
    smtp.Send(mail)
End Sub