Optie 1: System.Net.Mail.SmtpClient
Ingebouwd, maar als verouderd gemarkeerd voor nieuwe ontwikkeling — gebruik poort 587 met EnableSsl = true:
using System.Net;
using System.Net.Mail;
var apiKey = Environment.GetEnvironmentVariable("SENDCOREX_API_KEY")!;
using var client = new SmtpClient("smtp.sendcorex.com", 587)
{
EnableSsl = true,
Credentials = new NetworkCredential(apiKey, apiKey),
};
using var message = new MailMessage
{
From = new MailAddress("hello@yourdomain.com", "Your App"),
Subject = "Welcome!",
Body = "<h1>You are in.</h1>",
IsBodyHtml = true,
};
message.To.Add("customer@example.com");
await client.SendMailAsync(message);
Optie 2: MailKit (aanbevolen)
dotnet add package MailKit
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
var apiKey = Environment.GetEnvironmentVariable("SENDCOREX_API_KEY")!;
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Your App", "hello@yourdomain.com"));
message.To.Add(new MailboxAddress("", "customer@example.com"));
message.Subject = "Welcome!";
message.Body = new TextPart("html") { Text = "<h1>You are in.</h1>" };
using var smtp = new SmtpClient();
await smtp.ConnectAsync("smtp.sendcorex.com", 587, SecureSocketOptions.StartTls);
await smtp.AuthenticateAsync(apiKey, apiKey);
await smtp.SendAsync(message);
await smtp.DisconnectAsync(true);
Welke gebruik je?
Gebruik MailKit voor alle nieuwe code — het handelt TLS op elke poort correct af, is volledig async met annulering en wordt actief onderhouden. Houd SmtpClient alleen in bestaande code die je niet wilt aanraken.
Problemen oplossen
| Symptoom | Oplossing |
|---|---|
Authentication failed | Controleer of de env-variabele geladen is en als zowel username als password wordt gebruikt. |
SmtpProtocolException | Poort 465 vereist SslOnConnect, niet StartTls. |