Community编程与开发github.com

mjml-email-templates

使用MJML标记语言构建响应式电子邮件模板。编译为跨客户端HTML,可兼容Outlook、Gmail和Apple Mail。包括模板渲染器、布局模式和变量替换。

mjml-email-templates 是什么?

这是一个专注于电子邮件模板构建的AI技能,基于MJML标记语言。它帮助开发者解决电子邮件HTML渲染的痛点——不同邮件客户端(Outlook、Gmail、Apple Mail)渲染方式各异,通常需要复杂的基于表格的布局和内联样式。MJML通过简洁、可读的标记代码,自动编译生成跨客户端兼容的响应式HTML,显著降低开发难度。该技能支持在.NET应用程序中使用Mjml.Net库集成,提供完整的模板渲染流程:从加载布局模板和内容模板、合并变量、替换占位符到最终编译为HTML。技能还推荐了项目结构(如将模板作为嵌入资源)、布局模板与内容模板分离的设计模式、强类型值对象的电子邮件组合器模式,以及开发阶段的管理员预览端点。最佳实践涵盖了模板设计、变量处理、使用MJML组件而非原始HTML表格等关键建议。适用于构建交易邮件(如注册确认、密码重置、账单通知)以及任何需要跨客户端一致显示的电子邮件。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/mjml-email-templates

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

MJML 邮件模板

何时使用此技能

在以下场景中使用此技能:

  • 构建交易性邮件(注册、密码重置、发票、通知)
  • 创建跨客户端兼容的响应式电子邮件模板
  • 在.NET中设置MJML模板渲染

相关技能:

  • aspire/mailpit-integration - 使用Mailpit本地测试邮件
  • testing/verify-email-snapshots - 对渲染后的HTML进行快照测试

为什么选择MJML?

问题:电子邮件HTML编写非常困难。每个邮件客户端(Outlook、Gmail、Apple Mail)的渲染方式不同,需要复杂的基于表格的布局和内联样式。

解决方案:MJML 是一种标记语言,它编译生成响应式、跨客户端的HTML:

<!-- MJML - 简洁且易读 -->
<mj-section>
  <mj-column>
    <mj-text>你好 {{UserName}}</mj-text>
    <mj-button href="{{ActionUrl}}">点击此处</mj-button>
  </mj-column>
</mj-section>

编译后生成约200行基于表格的HTML,包含内联样式,可在任何地方正常工作。


安装

添加 Mjml.Net

dotnet add package Mjml.Net

将模板作为嵌入资源

在你的 .csproj 文件中:

<ItemGroup>
  <EmbeddedResource Include="Templates\**\*.mjml" />
</ItemGroup>

项目结构

src/
  Infrastructure/
    MyApp.Infrastructure.Mailing/
      Templates/
        _Layout.mjml              # 共享布局(页眉、页脚)
        UserInvitations/
          UserSignupInvitation.mjml
          InvitationExpired.mjml
        PasswordReset/
          PasswordReset.mjml
        Billing/
          PaymentReceipt.mjml
          RenewalReminder.mjml
      Mjml/
        IMjmlTemplateRenderer.cs
        MjmlTemplateRenderer.cs
        MjmlEmailMessage.cs
      Composers/
        IUserEmailComposer.cs
        UserEmailComposer.cs
      MyApp.Infrastructure.Mailing.csproj

布局模板 (_Layout.mjml)

<mjml>
  <mj-head>
    <mj-title>MyApp</mj-title>
    <mj-preview>{{PreviewText}}</mj-preview>
    <mj-attributes>
      <mj-all font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" />
      <mj-text font-size="14px" color="#555555" line-height="20px" />
      <mj-section padding="20px" />
    </mj-attributes>
    <mj-style inline="inline">
      a { color: #2563eb; text-decoration: none; }
      a:hover { text-decoration: underline; }
    </mj-style>
  </mj-head>
  <mj-body background-color="#f3f4f6">
    <!-- 页头 -->
    <mj-section background-color="#ffffff" padding-bottom="0">
      <mj-column>
        <mj-image
          src="https://myapp.com/logo.png"
          alt="MyApp"
          width="150px"
          href="{{SiteUrl}}"
          padding="30px 25px 20px 25px" />
      </mj-column>
    </mj-section>

    <!-- 在此处注入内容 -->
    <mj-section background-color="#ffffff" padding-top="20px" padding-bottom="40px">
      <mj-column>
        {{Content}}
      </mj-column>
    </mj-section>

    <!-- 页脚 -->
    <mj-section background-color="#f9fafb" padding="20px 25px">
      <mj-column>
        <mj-text align="center" font-size="12px" color="#9ca3af">
          &copy; 2025 MyApp Inc. 保留所有权利。
        </mj-text>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>

内容模板

<!-- UserInvitations/UserSignupInvitation.mjml -->
<!-- 自动包装在 _Layout.mjml 中 -->

<mj-text font-size="16px" color="#111827" font-weight="600" padding-bottom="20px">
  您已被邀请加入 {{OrganizationName}}
</mj-text>

<mj-text padding-bottom="15px">
  您好 {{InviteeName}},
</mj-text>

<mj-text padding-bottom="15px">
  {{InviterName}} 已邀请您加入 <strong>{{OrganizationName}}</strong>。
</mj-text>

<mj-text padding-bottom="25px">
  请点击下方按钮接受邀请:
</mj-text>

<mj-button background-color="#2563eb" color="#ffffff" font-size="16px" href="{{InvitationLink}}">
  接受邀请
</mj-button>

<mj-text padding-top="25px" font-size="13px" color="#6b7280">
  此邀请将于 {{ExpirationDate}} 过期。
</mj-text>

模板渲染器

public interface IMjmlTemplateRenderer
{
    Task<string> RenderTemplateAsync(
        string templateName,
        IReadOnlyDictionary<string, string> variables,
        CancellationToken ct = default);
}

public sealed partial class MjmlTemplateRenderer : IMjmlTemplateRenderer
{
    private readonly MjmlRenderer _mjmlRenderer = new();
    private readonly Assembly _assembly;
    private readonly string _siteUrl;

    public MjmlTemplateRenderer(IConfiguration config)
    {
        _assembly = typeof(MjmlTemplateRenderer).Assembly;
        _siteUrl = config["SiteUrl"] ?? "https://myapp.com";
    }

    public async Task<string> RenderTemplateAsync(
        string templateName,
        IReadOnlyDictionary<string, string> variables,
        CancellationToken ct = default)
    {
        // 加载内容模板
        var contentMjml = await LoadTemplateAsync(templateName, ct);

        // 加载布局并注入内容
        var layoutMjml = await LoadTemplateAsync("_Layout", ct);
        var combinedMjml = layoutMjml.Replace("{{Content}}", contentMjml);

        // 合并变量(布局 + 模板特定变量)
        var allVariables = new Dictionary<string, string>
        {
            { "SiteUrl", _siteUrl }
        };
        foreach (var kvp in variables)
            allVariables[kvp.Key] = kvp.Value;

        // 替换变量
        var processedMjml = SubstituteVariables(combinedMjml, allVariables);

        // 编译为HTML
        var result = await _mjmlRenderer.RenderAsync(processedMjml, null, ct);

        if (result.Errors.Any())
            throw new InvalidOperationException(
                $"MJML编译失败: {string.Join(", ", result.Errors.Select(e => e.Error))}");

        return result.Html;
    }

    private async Task<string> LoadTemplateAsync(string templateName, CancellationToken ct)
    {
        var resourceName = $"MyApp.Infrastructure.Mailing.Templates.{templateName.Replace('/', '.')}.mjml";

        await using var stream = _assembly.GetManifestResourceStream(resourceName)
            ?? throw new FileNotFoundException($"模板 '{templateName}' 未找到");

        using var reader = new StreamReader(stream);
        return await reader.ReadToEndAsync(ct);
    }

    private static string SubstituteVariables(string mjml, IReadOnlyDictionary<string, string> variables)
    {
        return VariableRegex().Replace(mjml, match =>
        {
            var name = match.Groups[1].Value;
            return variables.TryGetValue(name, out var value) ? value : match.Value;
        });
    }

    [GeneratedRegex(@"\{\{([^}]+)\}\}", RegexOptions.Compiled)]
    private static partial Regex VariableRegex();
}

邮件组合器模式

将模板渲染与邮件组合分离,使用强类型值对象:

public interface IUserEmailComposer
{
    Task<EmailMessage> ComposeSignupInvitationAsync(
        EmailAddress recipientEmail,
        PersonName recipientName,
        PersonName inviterName,
        OrganizationName organizationName,
        AbsoluteUri invitationUrl,
        DateTimeOffset expiresAt,
        CancellationToken ct = default);
}

public sealed class UserEmailComposer : IUserEmailComposer
{
    private readonly IMjmlTemplateRenderer _renderer;

    public UserEmailComposer(IMjmlTemplateRenderer renderer)
    {
        _renderer = renderer;
    }

    public async Task<EmailMessage> ComposeSignupInvitationAsync(
        EmailAddress recipientEmail,
        PersonName recipientName,
        PersonName inviterName,
        OrganizationName organizationName,
        AbsoluteUri invitationUrl,
        DateTimeOffset expiresAt,
        CancellationToken ct = default)
    {
        var variables = new Dictionary<string, string>
        {
            { "PreviewText", $"您已被邀请加入 {organizationName.Value}" },
            { "InviteeName", recipientName.Value },
            { "InviterName", inviterName.Value },
            { "OrganizationName", organizationName.Value },
            { "InvitationLink", invitationUrl.ToString() },
            { "ExpirationDate", expiresAt.ToString("yyyy年M月d日") }
        };

        var html = await _renderer.RenderTemplateAsync(
            "UserInvitations/UserSignupInvitation",
            variables,
            ct);

        return new EmailMessage(
            To: recipientEmail,
            Subject: $"您已被邀请加入 {organizationName.Value}",
            HtmlBody: html);
    }
}

邮件预览端点

添加一个管理端点,以便在开发期间预览邮件:

app.MapGet("/admin/emails/preview/{template}", async (
    string template,
    IMjmlTemplateRenderer renderer) =>
{
    var sampleVariables = GetSampleVariables(template);
    var html = await renderer.RenderTemplateAsync(template, sampleVariables);

    return Results.Content(html, "text/html");
})
.RequireAuthorization("AdminOnly");

最佳实践

模板设计

<!-- 正确做法:使用MJML组件进行布局 -->
<mj-section>
  <mj-column>
    <mj-text>内容</mj-text>
  </mj-column>
</mj-section>

<!-- 错误做法:使用原始HTML表格 -->
<table><tr><td>内容</td></tr></table>

<!-- 正确做法:使用生产环境的图片URL -->
<mj-image src="https://myapp.com/logo.png" />

<!-- 错误做法:使用相对路径 -->
<mj-image src="/img/logo.png" />

变量处理

// 正确做法:使用强类型值对象
Task<EmailMessage> ComposeAsync(
    EmailAddress to,
    PersonName name,
    AbsoluteUri actionUrl);

// 错误做法:使用原始字符串
Task<EmailMessage> ComposeAsync(
    string email,
    string name,
    string url);

MJML 组件参考

组件用途
<mj-section>水平容器(类似行)
<mj-column>部分内的垂直容器
<mj-text>带样式的文本内容
<mj-button>行动号召按钮
<mj-image>响应式图片
<mj-divider>水平分割线
<mj-spacer>垂直间距
<mj-table>数据表格
<mj-social>社交媒体图标

资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

相关技能