Opzione 1: System.Net.Mail.SmtpClient
Integrato, ma segnato come obsoleto per i nuovi sviluppi: usa la porta 587 con 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);
Opzione 2: MailKit (consigliato)
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);
Quale usare?
Usa MailKit per tutto il codice nuovo: gestisce correttamente il TLS su ogni porta, è completamente async con annullamento ed è mantenuto attivamente. Tieni SmtpClient solo nel codice esistente che non vuoi toccare.
Risoluzione dei problemi
| Sintomo | Soluzione |
|---|---|
Authentication failed | Verifica che la variabile d'ambiente sia caricata e usata sia come username sia come password. |
SmtpProtocolException | La porta 465 richiede SslOnConnect, non StartTls. |