5

I have written below code to embed image in the mail which is being sent from my c# code. But when i check the mail, i get image like an attachment and not as an inline image. (Gmail)

AlternateView htmlBodyView = null;

string htmlBody = "<html><body><h1></h1><br><img src=\"cid:SampleImage\"></body></html>";

AlternateView plainTextView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");

ImageConverter ic = new ImageConverter();
Byte[] ba = (Byte[])ic.ConvertTo(bitmap_obj, typeof(Byte[]));
using (MemoryStream logo = new MemoryStream(ba))
{
    LinkedResource sampleImage = new LinkedResource(logo, "image/jpeg");
    sampleImage.ContentId = "sampleImage";

    htmlBodyView.LinkedResources.Add(sampleImage);

    p.SendEmail(htmlBodyView);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Vikas Kottari
  • 495
  • 2
  • 10
  • 24
  • Please put more effort into formatting your code in future - check the preview to ensure that it appears how you'd want read it if *you* were trying to answer the question. – Jon Skeet Jun 08 '15 at 10:54
  • sure.. i will do that in all my future questions/ answers... thanks a lot – Vikas Kottari Jun 08 '15 at 10:56
  • Tried to find definitive source, so this may not be the issue, but looks like the ContentId is case sensitive and you've used `SampleImage` / `sampleImage'. https://tools.ietf.org/html/rfc2045 "Parameter values are normally case sensitive," – freedomn-m Jun 08 '15 at 14:02
  • Answer to this SO might help: http://stackoverflow.com/a/4697643/2181514 name format should like like an email address - but there's plenty of examples where this isn't the case – freedomn-m Jun 08 '15 at 14:15

1 Answers1

1

For reference, a full working simplified example:

    public void SendMail()
    {
        LinkedResource logo = new LinkedResource(
            "images\\image005.png",                 //Path of file
            "image/png");                           //Mime type: Important!
        logo.ContentId = "logo";                    //ID for reference

        //Actual HTML content of the body in an 'AlternateView' object.
        AlternateView vw = AlternateView.CreateAlternateViewFromString(
            "Hello, this is <b>HTML</b> mail with embedded image: <img src=\"cid:logo\" />", 
            null, 
            MediaTypeNames.Text.Html);              //Mime type: again important!
        vw.LinkedResources.Add(logo);

        var msg = new MailMessage() { IsBodyHtml = true };
        msg.AlternateViews.Add(vw);
        msg.From = new MailAddress("sender@domain.com");
        msg.To.Add(new MailAddress("reciever@domain.com"));
        msg.Subject = "HTML Mail!";
        using (var client = new SmtpClient("localhost", 25)) 
            client.Send(msg);
    }