Email templating engine - c#

I am about to write a simple email manager for the site I'm working on (asp.net/c#); the site sends out various emails, like on account creation, news, some user actions, etc. So there will be some email templates with placeholders like [$FirstName] which will be replaced by actual values. Pretty standard stuff. I'm just wondering if someone can advise on existing code - again, i need something very simple, without many bells/whistles, and obviously with source code (and free)
Any ideas/comments will be highly appreciated!
Thanks,
Andrey

There are several threads on Stack Overflow about this already, but I ended up rolling my own solution from various suggestions there.
I used this FormatWith extension method to take care of simple templating, and then I made a basic Email base class to take care of common tasks, like pulling in an appropriate template and replacing all the requisite info, as well as providing a Send() method.
All the emails I need to send have their own subclass deriving from the base, and define things unique to them, such as TemplateText, BindingData, Recipients, and Subject. Having them each in their own class makes them very easy to unit test idependently of the rest of the app.
So that your app can work with these email classes without really caring which one it's using, it's also a good idea to implement an interface, with any shared methods (the only one I cared about was Send()), so then your app can instantiate whatever email class it wants and work with them in the same way. Maybe generics could be used, too, but this was what I came up with.
IEmail email = new MyEmailClass();
email.Send();
Edit: There are many more suggestions here: Can I set up HTML/Email Templates with ASP.NET?

I always do the following. Templates = text string with {#} placeholders. To use a template I load the string (from whatever store) and then call string.Format(template,param1,param2..)
Simple and works well. When you need something stronger you can move to a framework of some kind but string.format has always worked well for me.
note
Alison R's link takes this method to the next step using 3.5's anonymous types to great effect. If you are 3.5 I recommend using the FormatWith there (I will) otherwise this way works well.

Having just done this myself, there is some great information at: Sending Email Both in HTML and Plain Text. Best part is, you don't need anything other than .NET.
Essentially, you create an HTML page (AKA, your formatted e-mail) with the tags that you want to replace (in the case of this solution, tags will be in the format of: <%TAGNAME%>). You then utilize the information found at the above website to create a mail template with the tags filled with the appropriate data, and the injections will be done for you into your HTML template. Then, you just use the SMTP classes built into .NET and send the mail on its way. It's very simple and straightforward.
Let me know if you have any additional questions. Hope that helps!

If you are using ASP.NET, you already have a templating engine available to you. Simply create an ASP.NET page that will produce the results for you (using whatever controls, etc, etc) you want, as well as setting the ContentType of the response to the appropriate type (either text or HTML, depending on the email format)
Make sure that this url is not publically exposed.
Then, in your code, you would create an HttpWebRequest/HttpWebResponse or WebClient and then fetch the URL and get the contents. The ASP.NET engine will process the request and return your formatted results, which you can then email.
If you want something simpler, why not use a RegEx and match? Just make sure you have a fairly unique identifer for your fields (prefix and suffix, which you can guarantee will never be used, or, you can at least write an escape sequence for it) and you could easily use the Match method to do the replace.
The only "gotcha" to the RegEx approach is that if you have to do embedded templating, then that's going to require a little more work.

Related

Stand-alone Error Page with translated text?

I'm working on a website that will deployed internationally. Very big site, but for the sake of simplicity, all we're concerned about is my Error.aspx with c# code behind. I'd like to make this custom error page as dynamic as possible. There's at least a handful of languages we need to read this page in right now, and more to come. This page needs to work independently and without a database to reference.
I'd like to have some text, and have the appropriate translation appear based on the language appropriate for that domain... e.g. ".com" = English, ".ca/fr" = French, ".mx" = Spanish... you get the idea.
What's the best way to do this?
I've looked into API's, but the decent ones have a cost threshold, and while it might look really helpful, this is just pretty standard error message text, that's unlikely to change, so that seems like overkill to have a dynamic translator. It might help with scalability, but it's extra money indefinitely, when it will only save vs hard-coding on the handful of occasions where we add another language/country/domain.
The other idea I had was to simply hardcode it in the c#. parse out Request.URL and get the domain, and make a ever-growing switch statement which would assign the appropriate text. (As an aside, I'm also trying to find a better way to do this, but is the country code something that would be an available piece of information from either the request object or server?) This way would be independent, precise, and the only drawback on a concrete level would be the cost of adding new languages, or changing every string (probably not that many, at least at first) if the content of the error message needed to be adjusted. But this feels like bad practice.
I've been researching this for a day now, but I haven't found any alternatives to these 2 options. What are the best practices for handling small amounts of text for translation, without the use of a CMS?
There is an easy built-in way to handle localization in ASP.NET Web Forms. It uses the Language Preference settings in the client's browser to select the language. Posting the steps of setting it up would be redundant since there's lots of information on this subject available online. Here is a good tutorial.
EDIT:
It might be a good idea to read up on HTML resource files. That is the HTML standard for handling different languages (referred to as localization). And it is what ASP.NET uses in the background when creating a local resource for a server control.

Email Templating Basics, with C#

I want to create my own email template without having to use third party software,I would just like to clear up some basics for my self :)
Firstly, do all email templates come down to pretty much being HTML body with inline CSS? Thus sending a templated email with C# would go somthing like:
SmtpClient smtpClient = new SmtpClient("smtphost");
MailMessage msg = new MailMessage();
msg.To.Add("toaddress6#place.com");
msg.Subject = "A TEMPLATE";
msg.Body = "<body> This is where the html goes O.o </body>";
msg.From = new MailAddress("fromaddress#anotherplace.com");
msg.IsBodyHtml = true;
smtpClient.Send(msg);
Secondly, sending images with a template I'm assuming they are either added on as an attachment or are linked to via a long address to the image location on the server, similar to a webpage? and displayed in the html.
I haven't tried it before, but take a look at the MailDefinition class.
Here's some solutions I have ran into while creating email templating systems:
There's no built-in templating system built into the framework that I know of. I built a system that worked pretty well in the past. Nowadays I do things simply. I would replace items like {year} with the current year, {year2} for a 2-digit year OR {year:2,} which is more work, but results in any of your variables to have the ability to do an inline SubString() without much work past the initial build. (you could do {var:name:upper}, :lower, :titlecase; you can pass in an object and use simple reflection techniques to read all the public properties and do automatic replacements... the sky is the limit!) The important thing is to give yourself a lot of leeway without violating the YAGNI principle too much. When you're building a system like this...
Start with examples of how you want to end up. I ended up writing something like <html><body><h1><font face="arial">Hello, <b>{var:firstname}!</b> It's {hour} {ampm} here...</font></h1> ...</html> which would do the replacements and spit out the final copy. Then, check using a regex that everything was replaced so you're not sending out Hi, null null! It's nice to see you at {hour} {ampm}! and make you the laughing stock of your recipients. Think hard about how you want to be able to insert content. You can do lots of crazy things with your own templating system, good and bad, so TEST TEST TEST. Unit tests are handy for regression testing. Remember, once you go live, you don't want to make mistakes since you're sending them to the customer and there's no way of changing it before the client sees it like you can do with a web site.
Most HTML newsletters are in HTML format, use inline-CSS or (gasp!) TABLEs and FONT tags for layout. The reason behind this is because most email HTML rendering engines are stuck in the past. What works with Thunderbird may work somewhat well with Mozilla, but will look like garbage in GMail or Hotmail. My recommendation is to use as little inline CSS as possible, and if you do, test with a few email clients, including web- and non-web-based clients to make sure you get the desired effect in each one. Use TABLEs for layout, no fancy CSS3 stuff. The KISS rule applies here, and yes, it's a blast from the past using the old-style HTML. You may feel like you need to take a shower after writing that horrible code, using tables for layout, etc., but that's what we need to do with what we are given.
Read this too: http://www.hongkiat.com/blog/design-perfect-newsletter/

ASP.NET MVC 3 Razor View Restrictions

I apologize in advance for the generic nature of my question, but I was unable to find any helpful advice from people trying to do the same thing as me on the web. Let me describe my scenario:
I am providing end users/designers of a website the ability to customize their views by storing the views (using Razor) in the database. I have all of this working, but my question is the following; From a security standpoint, how can I ensure and enforce that unwanted code doesn't get executed in the user-defined view? There are two basic approaches that I think will work conceptually, but am not sure which one is more possible or feasible.
Option 1: Create a validation method in the administration tool that allows the user to input the view code. This would need to either take a whitelist or blacklist approach to what is allowable or not.
Option 2: Prevent unwanted code from being able to execute when rendering of the view occurs.
As a quick example of something that would need to be blocked, we wouldn't want to allow access to read or write files, access any data access functions, or even access configuration settings, etc. in the web.config. There will likely be a decently-sized list of things that probably shouldn't be allowable, but I'll need to sit down and try to think of as many security-related concerns as possible.
My question then is, which method would be the best bet? Also, can any direction be provided on how to go about either? I thought I might be able to make trust-level based change which would be Option 2, but couldn't find any way to make that work in a per-view based manor (the administration code is allowed to execute whatever it wants). I'm thinking Option 1 will end up being the best bet and I'll have to check for the input of certain framework functions that shouldn't be allowed. Does anyone have any experience doing anything like what I'm trying to do? ANY feedback is much appreciated!
This would be extremely difficult.
You could run the the template through the Razor preprocessor, then use Roslyn (still in early beta) to parse the generated file and look through all method calls (or constructors) and return an error if it calls something you don't like.
I strongly recommend that you use a whitelist for that, since the .Net framework is big enough that you are bound to overlook something in a blacklist.
However, I would instead recommend that you not use Razor at all and instead use a templating engine that does not allow real C# code.

Removing previous part from Reply emails

I'm trying to write application that periodically receives e-mails. It writes every mail into database. But sometimes i'm getting 'Re:' e-mail that looks something like this:
New message
On September 21, 2010 24:26 Someone wrote (a):
| Old message
|
The format depends on e-mail provider.
Is there any library that helps removing 'Re' part from e-mail message? Maybe IMAP server can do that? I have all the previous e-mails from thread in database so I can take them and search in new message.
If you are able to associate a reply (RE:) message with the original/previous message that it is a reply to, then I would think that you could grab the body text of the original/previous message from your database, and then remove that text from the body of the reply. However, this method will not be 100% accurate, because clients could convert an HTML/Rich Text email in to plain text, or vice-versa. In any such case, this method probably wouldn't work. Even so, this technique would be generic and probably work the majority of the time.
In addition, the email provider may add certain header fields, or preambles, to the beginnings of a quoted message in a reply. In this case, I don't think there is any "catch all" solution.
My recommendation would be to target a few of the really huge web-mail providers (Gmail, Yahoo, Microsoft, etc), learn the formats that they use for their replies and parse the messages accordingly. In addition, you could likely handle a few generic formats as well. For instance, the '>' character is commonly used at the beginning of each line of quoted text in a reply.
If you're going to be developing in a language like C#, create yourself an Interface like IReplyFormat, with a corresponding implementation for each provider, and possibly some generic formats.
I don't think you will find any catch-all/perfect solution to this problem, as there are simply too many mail providers with too many different formats. However, I think you can at the very least find some techniques, like the ones mentioned above, that will work for you more times than not, which is the best you can hope for at this point.
Personally I think that you are out of luck here, as the message copy is part of the body. So in order to remove it you will have to process the message's body and write an extraction method for each known format (obviously the problem is that you cannot know all possible formats).
So, instead of parsing the body why don't you persist the whole message into the database? Normally the size of the message should not be the problem with modern DBMS. If it really is a problem you always can compress the body and store it in a BLOB.
No IMAP Server will not and does not remove anything
Such library does not exist because there is no standard, every email provider does it differently, gmail etc have developped their own tools
You have to look for pattern, that will somehow begin with headers with recipient as sender, like...
From: <receipent>
From: "NAME" <receipent>
From: receipent
and you have to omit the parts from this line below, howerver only checking this will not be sufficient as usually from is followed by subject,cc,to etc, so the pattern needs to be checked. I think some open source project or text library may exist, but its too difficult to find it on google.
I agree with Obalix. It's too hard to filter out replies so must keep the whole message. However, when you present email to the user, you can hide some parts of it. Those part can be shown with an optional "Click here to see the full message" or similar. For instance, regular expression to filter '>' characters would look something like #"^[ \f\t\v>]*"

making user friendly urls in a cms

I am interested in the architecture of a CMS where i can pass a full URL instead of a query string.
I would like to make a site that could handle a request to any page... Say
'http://www.my-domain.com/directory/page.aspx'
and have the resulting response deliver a generic page/file.
I would like the request to be passed through an XML document where i could store page names and the corresponding file to render content...
My question specifically
Is this possible
Is it easy to do
Are there any Links people have on
hand they could share with me on the
how to's.
Any pro's or
cons you may have come across if you
have used this method.
Yes, it's possible, and reasonable easy. Most CMSes do it this way, but use a database instead of an XML file.
You should probably look into URL rewriting. The concept is to separate the URL structure from the actual filesystem representation.
For .NET: UrlRewriting.Net is a gem.
However, since there are hundreds of fantastic CMSes already out there like you describe, I'd suggest using one of them and saving yourself work. Provide more detailed requirements and I can suggest one.

Categories