开发者

Action Mailer MVC3 - Send mail with user input

开发者 https://www.devze.com 2023-03-26 13:22 出处:网络
I am using ActionMailer to send emails with user input as follows: This is my MailController: public EmailResult VerificationEmail(EmailModel model)

I am using ActionMailer to send emails with user input as follows:

This is my MailController:

public EmailResult VerificationEmail(EmailModel model)
    {
          To.Add(model.To);
          From = model.From;
          Subject = model.Subject;
          return Email("VerificationEmail", model);
    }

This is my EmailModel:

public string To { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public string Body { get; set; }

This is my VerificationEmail.txt.cshtml

@model ...Models.EmailModel
@Model.Body

And this is my EmailModel view:

<div class="editor-field">
    @Html.TextAreaFor(x => x.Body)
    @Html.ValidationMessageFor(x => x.Body)
</div>

This works as intended, the user can modify the content of the email body and send customized emails. But what i'd like to achieve is let the user write something like:

Hello. The subject is: @Model.Subject

.. and see the correct output in the email sent. For example, if the EmailModel.Subject were "Gimme a million dollars!", then the email sent would be Hello. The subject is: Gimme a million dollars!

I can do this in the "VerificationEmail.thx.cshtml" and see the right output but i'd like to be able to do that directly in the EmailModel View's textarea.

Question is: how can i do that?开发者_JAVA技巧


I am not sure how to do it in the actionmailer but I do know how to do it using the RazorEngine project from Nuget. It will let you pass in a string template.

RazorEngine.Razor.Compile(template, typeof(EmailModel), "EmailModel")
var result = RazorEngine.Razor.Run<EmailModel>(model, "EmailModel")

Then just send the result as the body of an email.

This would be error prone if you are having the user make their own template inside the textarea, for example if they got the capitalization wrong when they typed @model. So if you use this method make sure to wrap it in some error handling.

0

精彩评论

暂无评论...
验证码 换一张
取 消