简体   繁体   中英

How can i get the path to an image file in wwwroot folder of an azure hosted asp .net core app inside a webjob

I am using an aspcore console app as a Webjob to send scheduled emails. In those emails i need to include an image from the wwwroot folder in the email headers. How can i get the url to that to pass into the src attribute of my img tag in the email html?

I test with txt file, to get the file path you could use HOME environment. It points to the D:\\home on the Kudu. So if your file is in wwwroot, you could use the below code to get it.

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

And the below is my sample code.

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

The below is my mail, and we could check the source code and find src="cid:weblogo" , this means the picture file is not a local file.

在此处输入图片说明

You could have a test with my code, hope this could help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM