简体   繁体   English

使用HTML和模型从MVC定制电子邮件页面

[英]Custom e-mail pages from MVC using HTML and model

I'm using "System.Net.Mail" to send e-mail in my code. 我正在使用“ System.Net.Mail”以我的代码发送电子邮件。 It allows the e-mail body to be sent as HTML. 它允许电子邮件正文以HTML格式发送。 I need to customize and decorate my e-mail using data from my model and also bootstrap. 我需要使用模型和引导程序中的数据来自定义和修饰电子邮件。

So, here I am, trying to create HTML pages and trying to integrate it with data from Model and then passing the HTML page as string to the "body" of the email object. 因此,在这里,我试图创建HTML页面,并尝试将其与Model中的数据集成,然后将HTML页面作为字符串传递给电子邮件对象的“正文”。

Does this make sense or is there any other way this can be done? 这有意义吗,或者还有其他方法可以做到吗?

PS: I'm trying to construct an HTML table, that gets rows dynamically based on data from the model. PS:我正在尝试构造一个HTML表,该表根据模型中的数据动态获取行。

I have always used this tool http://aboutcode.net/postal . 我一直使用此工具http://aboutcode.net/postal Try it out, it will save you lots of coding. 尝试一下,它将为您节省很多代码。

Here's an example. 这是一个例子。 I've even included some CSS to show how you can style your email. 我什至包括一些CSS来展示如何设置电子邮件样式。 "projects" is my model that I'm looping over to create the grid. “项目”是我正在遍历以创建网格的模型。

CSS support is limited in most email clients, so you may not be able to get Bootstrap to work, but you could try. 在大多数电子邮件客户端中,CSS支持是有限的,因此您可能无法使Bootstrap正常工作,但是可以尝试。 If not, you can still accomplish Bootstrap-like responsive design. 如果没有,您仍然可以完成类似Bootstrap的响应式设计。 The example below stays centered and 100% width as the page is resized. 下面的示例在调整页面大小时保持居中且宽度为100%。

var projects = db.Projects.Select(p => new { p.Name, p.Description } );

var grid = new StringBuilder();

foreach (var project in projects)
{
    grid.Append($@"<tr'>
            <td>{project.Name}</td>
            <td>{project.Description}</td>
        </tr>");
}

var body = $@"
    <style>
        body {{ color: #444 }}
        h2 {{ margin-top: 0; margin-bottom: 0 }}
        .container {{ text-align: center }}
        table {{ margin-left: auto; margin-right: auto; font-size: 20; width: 100% }}
        .heading {{ font-weight: bold; background-color: #f1f4ff }}
        td {{ padding-top: 8px; padding-bottom: 8px; padding-left: 16px; padding-right: 16px }}
    </style>

    <div class='container'>
        <h2>Hello from Mail</h2>

        <table class='grid' cellpadding='0' cellspacing='0'>
            <tr class='heading'>
                <td>Project Name</td>
                <td>Project Description</td>
            </tr>
            {grid}
        </table>
    </div>
";

client.Send(mail);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM