c# - 如何获取 webjob 内 azure 托管的 asp .net core 应用程序的 wwwroot 文件夹中图像文件的路径

标签 c# azure asp.net-core azure-webjobs

我正在使用 aspcore 控制台应用程序作为 Webjob 来发送计划的电子邮件。在这些电子邮件中,我需要在电子邮件标题中包含 wwwroot 文件夹中的图像。我怎样才能获得要传递到电子邮件 html 中的 img 标签的 src 属性中的 url?

最佳答案

我使用txt文件进行测试,以获取可以使用HOME环境的文件路径。它指向 Kudu 上的 D:\home。因此,如果您的文件位于 wwwroot 中,您可以使用以下代码来获取它。

Environment.GetEnvironmentVariable("HOME") + @"\site\wwwroot" + @"\test.jpg" 

下面是我的示例代码。

            string rootpath = null;

            rootpath = Environment.GetEnvironmentVariable("HOME") + @"\site\wwwroot" + @"\test.jpg";

            MailMessage mailMessage = new MailMessage();

            mailMessage.From = new MailAddress("xxxxxxxxxx");

            mailMessage.To.Add(new MailAddress("xxxxxxxxxxxx"));

            mailMessage.Subject = "message image test";

            mailMessage.IsBodyHtml = true;

            string content = "If your mail client does not support HTML format, please switch to the 'Normal Text' view and you will see this content.";
            mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content, null, "text/plain"));

            mailMessage.Body += "<br /><img src=\"cid:weblogo\">"; 

            AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(mailMessage.Body, null, "text/html");

            LinkedResource lrImage = new LinkedResource(rootpath, "image/jpg");

            lrImage.ContentId = "weblogo"; 

            htmlBody.LinkedResources.Add(lrImage);

            mailMessage.AlternateViews.Add(htmlBody);

            SmtpClient client = new SmtpClient();

            client.Host = "smtp.qq.com";

            client.EnableSsl = true;

            client.UseDefaultCredentials = false;

            client.Credentials = new NetworkCredential("xxxxxxxxxx", "xxxxxxxxxx");

            client.Send(mailMessage);

下面是我的邮件,我们查看源码可以发现src="cid:weblogo",说明图片文件不是本地文件。

enter image description here

您可以使用我的代码进行测试,希望这可以帮助您。

关于c# - 如何获取 webjob 内 azure 托管的 asp .net core 应用程序的 wwwroot 文件夹中图像文件的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56798651/

相关文章:

c# - .net 日历 requiredFieldValidator

c# - Asp.net Identity 2.0 临时密码

c# - 数据库未创建和初始化

powershell - 如何将 AAD 组设置为 AAD 应用程序的所有者?

azure - Azure 搜索 .NET 客户端 API 中的空间搜索

c# - 将连接字符串传递给 asp.net core 中的自定义 AuthorizeAttribute

c# - 在 ASP.NET vNext 中使用 Ninject 时出现编译器错误 CS0246(未找到类型或命名空间)

Javascript 不是从 Typescript 生成的

c# - 在我的项目中添加图像

Azure B2C登录: how to get access token in React SPA and without using the Azure login pop or login page?