3

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?

2
  • You could make a web request to your own website to that URL. But anyways, probably a bad idea. CSS in emails is very different from CSS on a webpage, because not all email client programs support the full range of CSS. The result might end up being an unreadable email. Commented Mar 25, 2015 at 17:08
  • @mason: Ah yes... didn't think of that... not ideal but could be a workaround until I find a better way. Thanks. Commented Mar 25, 2015 at 17:11

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.