Friday, April 29, 2011

Embbed photos to an Email

I am writing a Windows application which uses SMTP service to send email. I want to embed few dynamically created images to the Email content. How can I do this in .NET?. My format of email is HTML. I don't want to host my image to a photo hosting service. I don't want to send it as attachment.

From stackoverflow
  • Does this helps?

  • Here is some VB.NET code which should be trivial to change to C#. It will have to be attached. Thats the way HTML email works.

    http://www.example-code.com/vbdotnet/HtmlWithImage.asp

  • On your MailMessage object you need to create an alternative HTML view. Then you add LinkedResources to your alternative HTML view. The LinkedResource takes in a location of a file or a Stream object. Give the LinkedResource an ID which will match to whats in your HTML file.

    MailMessage msg = CreateYourMessage();
    msg.IsBodyHtml = true;
    
    string html = GetHtmlFromFileOrText();
    
    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(html, Encoding.UTF8, "text/html");
    
    LinkedResource img = new LinkedResource("location_of_image_or_stream_object");
    img.ContentId = "Header_Image";
    htmlView.LinkedResources.Add(img);
    
    message.AlternateViews.Add(htmlView);
    

    Your html file or text should have something like this

    < img src="cid:Header_Image" alt="" title="" />

    notice the cid should match the ContentID of your LinkedResource.

0 comments:

Post a Comment