how to send email wth email template c#

前端 未结 2 503
小蘑菇
小蘑菇 2020-12-12 23:10

suppose i need to send mail to customer with customer detail and his order detail. i have template html data in a html file.customer data is there and as well as order deta

相关标签:
2条回答
  • 2020-12-12 23:15

    As an alternative to MailDefinition, have a look at RazorEngine https://github.com/Antaris/RazorEngine.

    RazorEngine is a simplified templating framework built around Microsoft's new Razor parsing engine, used in both ASP.NET MVC3 and Web Pages. RazorEngine provides a wrapper and additional services built around the parsing engine to allow the parsing technology to be used in other project types.

    It lets you use razor templates outside of ASP.NET MVC and then write something like this (not tested):

    string template =
    @"<html>
    <body>
    Hi @Model.FirstName @Model.LastName,
    
    Here are your orders: 
    @foreach(var order in Model.Orders) {
        Order ID @order.Id Quantity : @order.Qty <strong>@order.Price</strong>. 
    }
    
    </body>
    </html>";
    
    var model = new OrderModel {
        FirstName = "Martin",
        LastName = "Whatever",
        Orders = new [] {
            new Order { Id = 1, Qty = 5, Price = 29.99 },
            new Order { Id = 2, Qty = 1, Price = 9.99 }
        }
    };
    
    string mailBody = Razor.Parse(template, model);
    
    0 讨论(0)
  • 2020-12-12 23:15

    You can't do such "complicated" logic with the default replacement stuff (the placeholder handling is made to be used for simple variables only, e.g. names or values).

    You'll have to do the parsing yourself. Depending on the complexity (e.g. loops withing loops), this can get a bit tricky.

    If you don't want or need such things, it's more trivial. E.g. use the regular expression \{foreach (.*?)\}(.*?)\{end\} to find such loops, then parse the contents/matched groups the way you need. Once that part is done, you could replace other values or use the default replacement feature.

    Only downside with this approach is the fact that you'll have to recreate the mail for each recipient (i.e. you can't mass mail using MailDefinition).

    0 讨论(0)
提交回复
热议问题