CommunityProgramación y desarrollogithub.com

Plantillas de Email con MJML

Construye plantillas de correo electrónico responsivas usando el lenguaje de marcado MJML. Compila a HTML compatible con múltiples clientes como Outlook, Gmail y Apple Mail. Incluye un renderizador de plantillas, patrones de diseño y sustitución de variables.

¿Qué es Plantillas de Email con MJML?

Esta habilidad permite a los desarrolladores crear y gestionar plantillas de correo electrónico responsivas utilizando MJML, un lenguaje de marcado diseñado específicamente para emails. Al compilar MJML a HTML, se garantiza la compatibilidad con los principales clientes de correo, incluyendo Outlook, Gmail y Apple Mail, evitando los problemas típicos de renderizado. La implementación está pensada para entornos .NET, utilizando la biblioteca Mjml.Net, e incluye un sistema completo de renderizado: las plantillas se almacenan como recursos incrustados, se combinan con un diseño compartido (_Layout.mjml) y se procesan mediante sustitución de variables. Además, se promueve el uso de un patrón de compositor (Composer Pattern) que separa la lógica de renderizado de la composición del mensaje, utilizando objetos fuertemente tipados para los valores (como nombres, correos o enlaces). La habilidad también proporciona instrucciones para la instalación, estructura de proyecto, ejemplos de plantillas de contenido y un endpoint de previsualización para desarrollo. En resumen, es una solución robusta y profesional para la generación de emails transaccionales (registro, restablecimiento de contraseña, facturas, notificaciones) con un flujo de trabajo claro y buenas prácticas.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/mjml-email-templates

Installed? Explore more Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

¿Qué hace Plantillas de Email con MJML?

Cuándo usar esta habilidad

Usa esta habilidad cuando:

  • Construyas correos transaccionales (registro, restablecimiento de contraseña, facturas, notificaciones)
  • Crear plantillas de correo electrónico responsivas que funcionen en todos los clientes
  • Configurar el renderizado de plantillas MJML en .NET

Habilidades relacionadas:

  • aspire/mailpit-integration - Prueba correos localmente con Mailpit
  • testing/verify-email-snapshots - Pruebas de instantáneas del HTML renderizado

Por qué MJML

Problema: El HTML de correos electrónicos es notoriamente difícil. Cada cliente de correo (Outlook, Gmail, Apple Mail) renderiza de manera diferente, requiriendo diseños complejos basados en tablas y estilos en línea.

Solución: MJML es un lenguaje de marcado que compila a HTML responsivo y compatible con múltiples clientes:

<!-- MJML - simple y legible -->
<mj-section>
  <mj-column>
    <mj-text>Hola {{NombreUsuario}}</mj-text>
    <mj-button href="{{UrlAccion}}">Haz clic aquí</mj-button>
  </mj-column>
</mj-section>

Compila a ~200 líneas de HTML basado en tablas con estilos en línea que funcionan en todas partes.


Instalación

Agregar Mjml.Net

dotnet add package Mjml.Net

Incrustar plantillas como recursos

En tu .csproj:

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

Estructura del proyecto

src/
  Infrastructure/
    MyApp.Infrastructure.Mailing/
      Templates/
        _Layout.mjml              # Diseño compartido (encabezado, pie de página)
        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

Plantilla de diseño (_Layout.mjml)

<mjml>
  <mj-head>
    <mj-title>MyApp</mj-title>
    <mj-preview>{{TextoVistaPrevia}}</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">
    <!-- Encabezado -->
    <mj-section background-color="#ffffff" padding-bottom="0">
      <mj-column>
        <mj-image
          src="https://myapp.com/logo.png"
          alt="MyApp"
          width="150px"
          href="{{UrlSitio}}"
          padding="30px 25px 20px 25px" />
      </mj-column>
    </mj-section>

    <!-- Contenido inyectado aquí -->
    <mj-section background-color="#ffffff" padding-top="20px" padding-bottom="40px">
      <mj-column>
        {{Contenido}}
      </mj-column>
    </mj-section>

    <!-- Pie de página -->
    <mj-section background-color="#f9fafb" padding="20px 25px">
      <mj-column>
        <mj-text align="center" font-size="12px" color="#9ca3af">
          &copy; 2025 MyApp Inc. Todos los derechos reservados.
        </mj-text>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>

Plantilla de contenido

<!-- UserInvitations/UserSignupInvitation.mjml -->
<!-- Se envuelve automáticamente en _Layout.mjml -->

<mj-text font-size="16px" color="#111827" font-weight="600" padding-bottom="20px">
  Has sido invitado a unirte a {{NombreOrganizacion}}
</mj-text>

<mj-text padding-bottom="15px">
  Hola {{NombreInvitado}},
</mj-text>

<mj-text padding-bottom="15px">
  {{NombreInvitador}} te ha invitado a unirte a <strong>{{NombreOrganizacion}}</strong>.
</mj-text>

<mj-text padding-bottom="25px">
  Haz clic en el botón de abajo para aceptar tu invitación:
</mj-text>

<mj-button background-color="#2563eb" color="#ffffff" font-size="16px" href="{{EnlaceInvitacion}}">
  Aceptar invitación
</mj-button>

<mj-text padding-top="25px" font-size="13px" color="#6b7280">
  Esta invitación expira el {{FechaExpiracion}}.
</mj-text>

Renderizador de plantillas

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)
    {
        // Cargar plantilla de contenido
        var contentMjml = await LoadTemplateAsync(templateName, ct);

        // Cargar diseño e inyectar contenido
        var layoutMjml = await LoadTemplateAsync("_Layout", ct);
        var combinedMjml = layoutMjml.Replace("{{Contenido}}", contentMjml);

        // Combinar variables (del diseño + específicas de la plantilla)
        var allVariables = new Dictionary<string, string>
        {
            { "UrlSitio", _siteUrl }
        };
        foreach (var kvp in variables)
            allVariables[kvp.Key] = kvp.Value;

        // Sustituir variables
        var processedMjml = SubstituteVariables(combinedMjml, allVariables);

        // Compilar a HTML
        var result = await _mjmlRenderer.RenderAsync(processedMjml, null, ct);

        if (result.Errors.Any())
            throw new InvalidOperationException(
                $"La compilación de MJML falló: {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($"Plantilla '{templateName}' no encontrada");

        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();
}

Patrón de compositor de correo

Separa el renderizado de la plantilla de la composición del correo con objetos de valor fuertemente tipados:

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>
        {
            { "TextoVistaPrevia", $"Has sido invitado a unirte a {organizationName.Value}" },
            { "NombreInvitado", recipientName.Value },
            { "NombreInvitador", inviterName.Value },
            { "NombreOrganizacion", organizationName.Value },
            { "EnlaceInvitacion", invitationUrl.ToString() },
            { "FechaExpiracion", expiresAt.ToString("MMMM d, yyyy") }
        };

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

        return new EmailMessage(
            To: recipientEmail,
            Subject: $"Has sido invitado a unirte a {organizationName.Value}",
            HtmlBody: html);
    }
}

Endpoint de previsualización de correo

Agrega un endpoint de administración para previsualizar correos durante el desarrollo:

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");

Mejores prácticas

Diseño de plantillas

<!-- HACER: Usar componentes MJML para el diseño -->
<mj-section>
  <mj-column>
    <mj-text>Contenido</mj-text>
  </mj-column>
</mj-section>

<!-- NO HACER: Usar tablas HTML en bruto -->
<table><tr><td>Contenido</td></tr></table>

<!-- HACER: Usar URLs de producción para imágenes -->
<mj-image src="https://myapp.com/logo.png" />

<!-- NO HACER: Usar rutas relativas -->
<mj-image src="/img/logo.png" />

Manejo de variables

// HACER: Usar objetos de valor fuertemente tipados
Task<EmailMessage> ComposeAsync(
    EmailAddress to,
    PersonName name,
    AbsoluteUri actionUrl);

// NO HACER: Usar cadenas en bruto
Task<EmailMessage> ComposeAsync(
    string email,
    string name,
    string url);

Referencia de componentes MJML

ComponentePropósito
<mj-section>Contenedor horizontal (como una fila)
<mj-column>Contenedor vertical dentro de la sección
<mj-text>Contenido de texto con estilo
<mj-button>Botón de llamada a la acción
<mj-image>Imagen responsiva
<mj-divider>Línea horizontal
<mj-spacer>Espaciado vertical
<mj-table>Tablas de datos
<mj-social>Iconos de redes sociales

Recursos

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.

Skills relacionados