I tried to send the email with an image in the body of email, the image is not an attachment.

I read the image from the media item in sitecore and i got the url of the image like https://domain/-/media/image.ashx next step i convert to email body using LinkedResource like below code

System.Net.Mail.LinkedResource imageResource = new 
System.Net.Mail.LinkedResource(imageUrl, "image/jpg");
imageResource.ContentId = "HDIImage";
System.Net.Mail.AlternateView htmlView = 
System.Net.Mail.AlternateView.CreateAlternateViewFromString("<image src=cid:" + 
imageResource.ContentId + ">" + textbody, null, "text/html");

but I have exception like the image path is not given correctly.

  • did you try to get the media URL with .jpg extension? Feb 7 '20 at 3:54
  • yes i tried convert .ashx into .jpg using Media.RequestAction , but i cannot able to convert that. Feb 7 '20 at 7:18
  • Taking a guess here , You should use this :- new StreamReader(MediaManager.GetMedia(sampleMedia).GetStream().Stream) Try to to convert media item to a stram and assign to LinkedResource constructor, I am hoping the constructor allows that
    – Abhay Dhar
    Feb 7 '20 at 11:30
  • Thank you Abhay Dhar, Url has been convert into Stream now i can able to send image with body Feb 10 '20 at 8:35

Now, I got an answer to my question. It is helpful to other developers.

Sitecore.Data.Items.MediaItem image = new Sitecore.Data.Items.MediaItem(imageField.MediaItem); string mimetype=image.MimeType; Stream stream = MediaManager.GetMedia(image).GetStream().Stream;

In this stage, I got an image as a stream

Next, I created the email

//Create two views, one text, one HTML. var bodyMail="Test Message";

//Add image to HTML version System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(stream ); imageResource.ContentId = "HDIImage"; System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("" + textbody, null, "text/html");

htmlView.LinkedResources.Add(imageResource); //Add two views to message. msg.AlternateViews.Add(htmlView);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.