0

I have the following function that generates the body of an email based on an HTML file:

private string createEmailBody(string userName, string title, string message)  
{  
    string body = string.Empty;  
    //using streamreader for reading my htmltemplate   

    using(StreamReader reader = new StreamReader(Server.MapPath("~/HtmlTemplate.html")))  
    {  
        body = reader.ReadToEnd();  
    }  
    body = body.Replace("{UserName}", userName); //replacing the required things  
    body = body.Replace("{Title}", title);  
    body = body.Replace("{message}", message);  
    return body;  
} 

This function was written a few years ago. Is there any newer way to send HTML formatted email? (I researched in SO but found only old questions from 5 years ago and more.)

I'm using this code in my Web API to send confirmation emails to new registers.

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
user3378165
  • 6,546
  • 17
  • 62
  • 101
  • possible duplicate http://stackoverflow.com/questions/1329922/send-html-email-via-c-sharp-with-smtpclient and http://stackoverflow.com/questions/8628683/how-to-send-html-formatted-email – Oscar Lundberg Jan 22 '17 at 11:40
  • Thank you, I saw these questions but they are all asked a few years ago (2012, 2009 etc..) – user3378165 Jan 22 '17 at 11:42
  • @user3378165 Explain how they don't answer your question? Because as far as I can see they do, and then it doesn't matter when they were asked. – Oscar Lundberg Jan 22 '17 at 11:45
  • @OscarLundberg I don't ask how to send a HTML formatted email, I have a code that do that and working properly, I just ask if since 5 years ago is there any new "modern" way to do that. – user3378165 Jan 22 '17 at 11:47
  • The code is generally fine, but you should sanitize user input using for example `WebUtility.HtmlEncode(unencoded);` – NineBerry Jan 22 '17 at 11:49
  • Razor? http://mehdi.me/generating-html-emails-with-razorengine-basics-generating-your-first-email/ – Squiggs. Jan 22 '17 at 12:11
  • @Paul, will that work in a Web API? – user3378165 Jan 22 '17 at 12:19
  • Sure @user3378165 - http://www.mikesdotnetting.com/article/261/integrating-web-api-with-asp-net-razor-web-pages – Squiggs. Jan 22 '17 at 12:25
  • Following on from @Paul, if you're looking for a super cut down version of Razor to parse email templates, I'd look at the RazorEngine. It's a few lines of code to implement and it also offers caching of templates to work super quick. https://github.com/Antaris/RazorEngine – Christopher Thomas Jan 23 '17 at 03:57

0 Answers0