c# asp.net 发送电子邮件模板 html

c# asp.net Send email template html

提问人:sandro vieira 提问时间:10/19/2022 最后编辑:Xinran Shensandro vieira 更新时间:11/15/2023 访问量:1199

问:

我有一个 asp.net Web 应用程序来发送电子邮件,并且我尝试发送一个 html 文件模板。我可以发送我的文件,但模板中的图像不会加载到发送的消息中!

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");                               
        }

 }

...

我的htmltemplate是这样的:

    <!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>

... 当我发送这个html文件时,只加载了最后一张图像。

有什么想法吗?

C# asp.net ASP.NET-Core 电子邮件 ASP.NET-web-API

评论


答:

0赞 Xinran Shen 10/19/2022 #1

有两种方法,一种是将图片上传到服务器进行公开,另一种是将图片编码为 base64。

我将在这里展示第二种方法。

首先,选择一个(网站),将图像编码为 base64。transcoding website

二、用途:

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

在您的模板 HTML 中。

然后图像将加载到电子邮件中。

enter image description here

enter image description here

1赞 Tut 10/19/2022 #2
<img src="http://localhost:1114/WebBody/Images/image2.jpg">

第一个图像不是公开的,它仅在本地 IISExpress 中。收件人无权访问此地址“//localhost:1114/WebBody/Images/image2.jpg”。您需要将其放在公共主机(例如某些映像托管)中,或者如果您在 Intranet 环境中,则将其上传到 IIS 目录。

这显然是在公共领域https://cdn.mos.cms.futurecdn.net/FVqUjfbiHS9imyJiRiM53-970-80.jpg.webp