Zum Inhalt springen

Sending emails with Mailpit

Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.

⭐ Community Toolkit Mailpit logo

To get started with the Aspire Mailpit integrations, follow the Get started with Mailpit integrations guide.

Mailpit doesn’t require a dedicated client integration package. You can use any SMTP library to send emails to Mailpit. The connection information is automatically injected into your application when you reference the Mailpit resource.

Here’s an example using the popular MailKit library:

Terminal window
dotnet add package MailKit
using MailKit.Net.Smtp;
using MimeKit;
public class EmailService
{
private readonly string _smtpHost;
public EmailService(IConfiguration configuration)
{
_smtpHost = configuration.GetConnectionString("mailpit")?.Split(':')[0] ?? "localhost";
}
public async Task SendEmailAsync(string to, string subject, string body)
{
using var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sender", "sender@example.com"));
message.To.Add(new MailboxAddress("Recipient", to));
message.Subject = subject;
message.Body = new TextPart("plain") { Text = body };
using var client = new SmtpClient();
await client.ConnectAsync(_smtpHost, _smtpPort, false);
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
}

You can also use the built-in System.Net.Mail APIs:

using System.Net;
using System.Net.Mail;
public class EmailService
{
private readonly string _smtpHost;
public EmailService(IConfiguration configuration)
{
_smtpHost = configuration.GetConnectionString("mailpit")?.Split(':')[0] ?? "localhost";
}
public async Task SendEmailAsync(string to, string subject, string body)
{
using var client = new SmtpClient(_smtpHost, _smtpPort);
using var message = new MailMessage("sender@example.com", to, subject, body);
await client.SendMailAsync(message);
}
}