Community程式設計與開發github.com

mjml-email-templates

使用 MJML 標記語言建立跨用戶端響應式電子郵件範本,支援範本渲染、佈局模式和變數取代。

mjml-email-templates 是什麼?

此技能提供使用 MJML 構建跨客戶端響應式電子郵件範本的完整解決方案。它涵蓋了從專案結構、佈局範本到內容範本的設計,並透過 `Mjml.Net` 函式庫整合到 .NET 應用程式中。核心功能包括一個 `IMjmlTemplateRenderer` 介面及其實作,負責載入 MJML 範本、合併佈局與內容、取代變數,最後編譯成相容於 Outlook、Gmail 和 Apple Mail 的 HTML。此外,還提供了強型別的電子郵件組合器模式 (`IUserEmailComposer`),用於分離範本渲染與郵件組合邏輯,並包含開發階段的郵件預覽端點。此技能適用於建立交易型郵件(如註冊、密碼重設、發票、通知),並推薦與 `aspire/mailpit-integration`(本地測試郵件)和 `testing/verify-email-snapshots`(快照測試)搭配使用。

相容平台~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.

相關技能