Communityコーディング&開発github.com

mjml-email-templates

MJMLマークアップ言語を使用してレスポンシブなメールテンプレートを構築します。Outlook、Gmail、Apple Mailで動作するクロスクライアントHTMLにコンパイルします。テンプレートレンダラー、レイアウトパターン、変数置換機能を含みます。

mjml-email-templates とは?

このスキルは、Mjml.Netライブラリを使用して、.NETプロジェクト内でMJMLベースのレスポンシブメールテンプレートをレンダリングするための堅牢なフレームワークを提供します。MJMLは、メールクライアント間の互換性の問題を抽象化し、開発者が使いやすいマークアップでテンプレートを作成できるようにし、数行のコードからクライアント対応の複雑なHTMLを生成します。このスキルには、共有レイアウトテンプレート、コンテンツ固有のテンプレート、強く型付けされた値オブジェクトを使用した変数置換、テンプレートレンダリングとメール作成を分離するためのクリーンなコンポーザーパターンが含まれています。主な機能には、埋め込みリソースからのテンプレート読み込み、レイアウトとコンテンツの結合、`{{変数名}}`構文による動的コンテンツ注入、開発用のメールプレビューエンドポイント、およびMJMLコンポーネント(`<mj-section>`、`<mj-column>`、`<mj-button>`など)のベストプラクティスが含まれます。このスキルは、.NETアプリケーション(特にASP.NET Core)で使用するために設計されており、Claude Code、Coder、またはCursorなどのAIエージェントが、トランザクションメール機能を実装するときに一貫性のある高品質なメールテンプレートシステムを生成できるようにします。

対応~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に質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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. All rights reserved.
        </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", $"You've been invited to join {organizationName.Value}" },
            { "InviteeName", recipientName.Value },
            { "InviterName", inviterName.Value },
            { "OrganizationName", organizationName.Value },
            { "InvitationLink", invitationUrl.ToString() },
            { "ExpirationDate", expiresAt.ToString("MMMM d, yyyy") }
        };

        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.

関連スキル