我正在使用 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"
,说明图片文件不是本地文件。
您可以使用我的代码进行测试,希望这可以帮助您。
关于c# - 如何获取 webjob 内 azure 托管的 asp .net core 应用程序的 wwwroot 文件夹中图像文件的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56798651/