Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read CSS content from bundle in code in an ASP.NET MVC website

I have a website, that uses bootstrap and a bootstrap theme. My website also sends out notification emails to users of the website when they trigger certain actions.

I want the body of a notification email that is sent out to be nicely formatted HTML content with the same look and feel as the main website.

I've always been taught to write DRY code, and make things as maintainable as possible, so I want to include the same bootstrap CSS that my website uses as an embedded file in the email, and have the HTML body reference that CSS, so that if I decide to change the theme of my website, it automatically re-styles my notification emails.

I'm using System.Net.Mail.SmtpClient to send the email, and adding content using AlternateViews. I don't want to include a live reference back to my site's css incase the email is viewed offline, so I want to embed the css.

I'm stuck with how to read the CSS file into a string, and attach it to the email. In my BundleConfig, I have this:

bundles.Add(new StyleBundle("~/Content/css").Include(
          "~/Content/bootstrap-sandstone.css",
          "~/Content/site.css"));

So I tried:

var css = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Content/css"));

But as I thought might happen, it threw a FileNotFound exception.

What can I use that will let me pass in ~/Content/css and out pops the css?

like image 559
BG100 Avatar asked Dec 13 '25 16:12

BG100


1 Answers

I found a way to grab the CSS content using this code:

var cssBundle = BundleTable.Bundles.GetBundleFor("~/Content/css");
var css = cssBundle.GenerateBundleResponse(new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, string.Empty)).Content;

However, as mason predicted (in the comments) the CSS doesn't work in the email, and it's far too large, so I'm going to simply embed basic CSS in the HTML.

like image 143
BG100 Avatar answered Dec 15 '25 10:12

BG100



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!