gvivet applus gvivet applus - 2 months ago 48
ASP.NET (C#) Question

Add Attachment base64 image in MailMessage and read it in html body

Currently I have to send emails with

MailMessage
and
SmtpClient
but I need to send a picture that is currently in
base64
string
within the
MailAddress
body.

I have understood that it is necessary to put it in the
Attachment
, but I don't know how to put
base64
in
MailMessage
class and then read it in order to visualize image in the body of the email. I don't have url image path.

Answer

To embed image into your mail message: (Its not same as adding an attachment file to message)

You dont need to convert image to base64 if you are using system.net.mail namespace to send your mail.

var mail = new MailMessage();
var imageToInline = new LinkedResource("Your image full path", MediaTypeNames.Image.Jpeg);
            imageToInline.ContentId = "MyImage";
            alternateView.LinkedResources.Add(imageToInline);
mail.AlternateViews.Add(body);

Update:

This is somewhat hacky way of embedding image to your mailMessage.

Byte[] bitmapData = Convert.FromBase64String(FixBase64ForImage("Your base64 image string"));
System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);

public static string FixBase64ForImage(string Image)
{
        System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image, Image.Length);
        sbText.Replace("\r\n", string.Empty); sbText.Replace(" ", string.Empty);
        return sbText.ToString();
}


var mail = new MailMessage();
var imageToInline = new LinkedResource(streamBitmap , MediaTypeNames.Image.Jpeg);
imageToInline.ContentId = "MyImage";
alternateView.LinkedResources.Add(imageToInline);
mail.AlternateViews.Add(body);

And your html mail body should have following tag:

 <img alt ="" src ="cid:MyImage"/>