Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linked resource does not come as inline image C#

Tags:

c#

mailmessage

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);
}
like image 779
Vikas Kottari Avatar asked Nov 09 '22 11:11

Vikas Kottari


1 Answers

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("[email protected]");
        msg.To.Add(new MailAddress("[email protected]"));
        msg.Subject = "HTML Mail!";
        using (var client = new SmtpClient("localhost", 25)) 
            client.Send(msg);
    }
like image 143
André Boonzaaijer Avatar answered Nov 14 '22 22:11

André Boonzaaijer