Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return ASP.NET MVC View as HTML File for use in email Template

I am building an application which will send out custom emails to end users.

I have constructed an HTML template from which the emails will be built.

I currently have the template filled with tags as placeholders for the custom content...

|Text-Placeholder|

I have been returning the html file as a string to my CreateEMail Method:

string html = System.IO.File.ReadAllText(Server.MapPath("~/EmailTemplates/emailTemplate.html"));

And then using String.Replace to substitute in the custom text/content

html = html.Replace("|Name-Placeholder|", username);

I am curious if there is a method which would allow me to construct the template as a RazorView strongly typed as a ViewModel which will model the custom text/content, and return the view as an HTML file or directly as a string to pass into the body property of my SMTPClient instance for sending to the user?

Has anyone accomplished something like this or similar?

like image 269
stephen776 Avatar asked Jan 13 '12 15:01

stephen776


1 Answers

Have a look at these libraries:

There is ActionMailer. Inspired by Ruby's ActionMailer.

ActionMailer.Net aims to be an easy, and relatively painless way to send email from your ASP.NET MVC application. The concept is pretty simple. We render HTML by utilizing some pretty snazzy view engines, so why can't we do the same thing for email?

http://nuget.org/packages/ActionMailer

Supports many view engines I think, Razor included of course. And allows you to pass a model into the view. See: https://bitbucket.org/swaj/actionmailer.net/wiki/Home

The code :

public class MailController : MailerBase
{
    public EmailResult VerificationEmail(User model)
    {
        To.Add(model.EmailAddress);
        From = "[email protected]";
        Subject = "Welcome to My Cool Site!";
        return Email("VerificationEmail", model);
    }
}

The view:

@using ActionMailer.Net
@model User
@{
    Layout = null;
}
Welcome to My Cool Site, @Model.FirstName. We need you to verify your email.
Click this nifty link to get verified!

There is also another library:

MvcMailer lets you use your MVC Views to produce stunning emails

http://nuget.org/packages/MvcMailer
https://github.com/smsohan/MvcMailer

like image 94
gideon Avatar answered Sep 24 '22 20:09

gideon