Search code examples
c#asp.netasp.net-coreemailasp.net-web-api

c# asp.net Send email template html


I have an asp.net web app to send emails, and I have tried to send an html file template. I can send my file, but the images from the template dont load on the message sent!

public void SendEmail(string EmailAddress)    
{

      try
        {

            MailMessage mail = new MailMessage();
            mail.To.Add(EmailAddress);
            mail.From = new MailAddress("[email protected]");
            mail.Subject = txtSubject.Text;
            
            string FilePath = Server.MapPath("templateHtml.html");
            StreamReader str = new StreamReader(FilePath);
            string body = str.ReadToEnd();
            //string body = Server.HtmlEncode(str.ReadToEnd());

            mail.IsBodyHtml = true;
            mail.Body = body;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = smtpClient;
            smtp.Credentials = new NetworkCredential(email, password);
            
            smtp.EnableSsl = true;
            smtp.Send(mail);
            str.Close();
            Response.Write("ok!")
        }
    catch
        {                
            Response.Write("so bad");                               
        }

 }

...

My htmltemplate is like:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title></title>
    </head>
    <body>

    <br />
    <p>This is an image</p>
    <img src="Images/image1.jpg">

    <p>This is an image</p>
    <img src="http://localhost:1114/WebBody/Images/image2.jpg">

    <p>image from net</p>
    <img src="https://cdn.mos.cms.futurecdn.net/FVqUjfbiHS9imyJiRiM53-970-80.jpg.webp" width="40%">

    </body>
    </html>

... When I send this html file, just the last image is loaded.

Any ideas?


Solution

  • There are two ways, one is to upload the image to the server to make it public, the other is to encode the image to base64.

    I will show the second method here.

    First, Choose a transcoding website(website), Encoding the image to base64.

    Second, Use:

    <img src='data:image/jpeg;base64,  <!-- Base64 data --> />
    

    in your template html.

    Then the image will load in email.

    enter image description here

    enter image description here