Modèles d'Emails MJML
Quand Utiliser Cette Compétence
Utilisez cette compétence quand :
- Vous construisez des emails transactionnels (inscription, réinitialisation de mot de passe, factures, notifications)
- Vous créez des modèles d'emails responsives fonctionnant sur tous les clients
- Vous mettez en place un rendu de template MJML en .NET
Compétences connexes :
aspire/mailpit-integration- Testez les emails localement avec Mailpittesting/verify-email-snapshots- Testez par snapshot le HTML rendu
Pourquoi MJML ?
Problème : Le HTML des emails est notoirement difficile. Chaque client email (Outlook, Gmail, Apple Mail) rend différemment, nécessitant des mises en page complexes basées sur des tableaux et des styles en ligne.
Solution : MJML est un langage de balisage qui compile en HTML responsive et multi-client :
<!-- MJML - simple et lisible -->
<mj-section>
<mj-column>
<mj-text>Bonjour {{UserName}}</mj-text>
<mj-button href="{{ActionUrl}}">Cliquez ici</mj-button>
</mj-column>
</mj-section>
Compile en ~200 lignes de HTML basé sur des tableaux avec styles en ligne qui fonctionne partout.
Installation
Ajouter Mjml.Net
dotnet add package Mjml.Net
Intégrer les Templates comme Ressources
Dans votre .csproj :
<ItemGroup>
<EmbeddedResource Include="Templates\**\*.mjml" />
</ItemGroup>
Structure du Projet
src/
Infrastructure/
MyApp.Infrastructure.Mailing/
Templates/
_Layout.mjml # Mise en page partagée (en-tête, pied de page)
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
Modèle de Mise en Page (_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">
<!-- En-tête -->
<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>
<!-- Contenu injecté ici -->
<mj-section background-color="#ffffff" padding-top="20px" padding-bottom="40px">
<mj-column>
{{Content}}
</mj-column>
</mj-section>
<!-- Pied de page -->
<mj-section background-color="#f9fafb" padding="20px 25px">
<mj-column>
<mj-text align="center" font-size="12px" color="#9ca3af">
© 2025 MyApp Inc. Tous droits réservés.
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>
Modèle de Contenu
<!-- UserInvitations/UserSignupInvitation.mjml -->
<!-- Enveloppé automatiquement dans _Layout.mjml -->
<mj-text font-size="16px" color="#111827" font-weight="600" padding-bottom="20px">
Vous avez été invité à rejoindre {{OrganizationName}}
</mj-text>
<mj-text padding-bottom="15px">
Bonjour {{InviteeName}},
</mj-text>
<mj-text padding-bottom="15px">
{{InviterName}} vous a invité à rejoindre <strong>{{OrganizationName}}</strong>.
</mj-text>
<mj-text padding-bottom="25px">
Cliquez sur le bouton ci-dessous pour accepter votre invitation :
</mj-text>
<mj-button background-color="#2563eb" color="#ffffff" font-size="16px" href="{{InvitationLink}}">
Accepter l'invitation
</mj-button>
<mj-text padding-top="25px" font-size="13px" color="#6b7280">
Cette invitation expire le {{ExpirationDate}}.
</mj-text>
Moteur de Rendu des Templates
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)
{
// Charger le template de contenu
var contentMjml = await LoadTemplateAsync(templateName, ct);
// Charger la mise en page et injecter le contenu
var layoutMjml = await LoadTemplateAsync("_Layout", ct);
var combinedMjml = layoutMjml.Replace("{{Content}}", contentMjml);
// Fusionner les variables (mise en page + spécifiques au template)
var allVariables = new Dictionary<string, string>
{
{ "SiteUrl", _siteUrl }
};
foreach (var kvp in variables)
allVariables[kvp.Key] = kvp.Value;
// Substituer les variables
var processedMjml = SubstituteVariables(combinedMjml, allVariables);
// Compiler en HTML
var result = await _mjmlRenderer.RenderAsync(processedMjml, null, ct);
if (result.Errors.Any())
throw new InvalidOperationException(
$"La compilation MJML a échoué : {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($"Template '{templateName}' introuvable");
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();
}
Pattern de Composition d'Email
Séparez le rendu du template de la composition de l'email avec des objets valeur fortement typés :
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", $"Vous avez été invité à rejoindre {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: $"Vous avez été invité à rejoindre {organizationName.Value}",
HtmlBody: html);
}
}
Point de Terminaison de Prévisualisation des Emails
Ajoutez un point de terminaison administrateur pour prévisualiser les emails pendant le développement :
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");
Bonnes Pratiques
Conception des Templates
<!-- À FAIRE : Utiliser les composants MJML pour la mise en page -->
<mj-section>
<mj-column>
<mj-text>Contenu</mj-text>
</mj-column>
</mj-section>
<!-- À NE PAS FAIRE : Utiliser des tableaux HTML bruts -->
<table><tr><td>Contenu</td></tr></table>
<!-- À FAIRE : Utiliser des URLs de production pour les images -->
<mj-image src="https://myapp.com/logo.png" />
<!-- À NE PAS FAIRE : Utiliser des chemins relatifs -->
<mj-image src="/img/logo.png" />
Gestion des Variables
// À FAIRE : Utiliser des objets valeur fortement typés
Task<EmailMessage> ComposeAsync(
EmailAddress to,
PersonName name,
AbsoluteUri actionUrl);
// À NE PAS FAIRE : Utiliser des chaînes brutes
Task<EmailMessage> ComposeAsync(
string email,
string name,
string url);
Référence des Composants MJML
| Composant | Objectif |
|---|---|
<mj-section> | Conteneur horizontal (comme une ligne) |
<mj-column> | Conteneur vertical dans une section |
<mj-text> | Contenu textuel avec styles |
<mj-button> | Bouton d'appel à l'action |
<mj-image> | Image responsive |
<mj-divider> | Ligne horizontale |
<mj-spacer> | Espacement vertical |
<mj-table> | Tableaux de données |
<mj-social> | Icônes de médias sociaux |
Ressources
- Documentation MJML : https://documentation.mjml.io/
- Bac à sable MJML : https://mjml.io/try-it-live
- Mjml.Net : https://github.com/ArtZab/Mjml.Net