0

我正在开发一个.NET MVC3 Web 应用程序 在此我的目标是发送预定的电子邮件,我将在其中使用电子邮件模板。我很困惑我应该遵循什么来实现我的目标。

我试过了MVC Mailer。但它不适用于调度程序。(流利的调度程序)我尝试使用RazorEngine电子邮件模板,但不知何故未能成功附加HTML Email Templates.

请帮忙...

4

1 回答 1

1

使用RazorEngine这样的东西应该会有所帮助,非常简单:

public bool SendEmailMessage(string template, object viewModel, string to, string @from, string subject, params string[] replyToAddresses)
    {
       var compiledTemplate = LoadTemplate(template, viewModel);

       return  SendEmail(from, to, subject, compiledTemplate, from, null, replyToAddresses);

    }

public bool SendEmailMessageWithAttachments(string template, object viewModel, string to, string @from, string subject, List<Attachment> attachedFiles, params string[] replyToAddresses)
        {
            var compiledTemplate = LoadTemplate(template, viewModel);
            return SendEmail(from, to, subject, compiledTemplate, from, attachedFiles, replyToAddresses);
        } 

 public string LoadTemplate(string template, object viewModel)
        {
            var templateContent = AttemptLoadEmailTemplate(template);
            var compiledTemplate = Razor.Parse(templateContent, viewModel);

            return compiledTemplate;
        }

    private string AttemptLoadEmailTemplate(string name)
    {
        if (File.Exists(name))
        {
            var templateText = File.ReadAllText(name);
            return templateText;
        }

        var templateName = string.Format("~/Data/EmailTemplates/{0}.html", name); //Just put your path to a scpecific template
        var emailTemplate = HttpContext.Current.Server.MapPath(templateName);

        if (File.Exists(emailTemplate))
        {
            var templateText = File.ReadAllText(emailTemplate);
            return templateText;
        }

        return null;
    }

    private bool SendEmail(string from, string to, string subject, string body, string replyTo, List<Attachment> attachedFiles, params string[] replyToAddresses)
            {
                replyTo = replyTo ?? from;
                attachedFiles = attachedFiles ?? new List<Attachment>();

                var message = new MailMessage(from, to, subject, body);
                message.ReplyToList.Add(replyTo);

                foreach (var attachedFile in attachedFiles)
                    message.Attachments.Add(attachedFile);

        try
        {
            smtpClient.SendAsync(email, null);
            return true;
        }
        catch (Exception exption)
        {
            return false;
        }
      }

希望能帮助到你

编辑:

假设您有一个名为“TestTemplate”的模板:

亲爱的@Model.Name

想象一下,如果这是一个普通的 cshtml 视图,并把你的模型属性像这样:@Model.SomeProperty

干杯。

使用位于我在辅助方法 AttempLoadEmailTemplate 中作为前缀的路径中的上一个模板,您可以发送这样的电子邮件:

var viewModel = new { Name = "Aks", SomeProperty = "Foo" };

mailService.SendEmailMessage("TestTemplate", viewModel, "aks@gmail.com", "daniel@gmail.com", "testing razor engine", null);
于 2013-12-11T14:53:19.967 回答