Opção 1: System.Net.Mail.SmtpClient
Nativo, mas marcado como obsoleto para novos projetos — use a porta 587 com 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);
Opção 2: MailKit (recomendado)
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);
Qual usar?
Use MailKit em todo código novo — ele trata TLS corretamente em todas as portas, é totalmente async com cancelamento e é mantido ativamente. Mantenha o SmtpClient só no código existente que você não quer mexer.
Solução de problemas
| Sintoma | Solução |
|---|---|
Authentication failed | Confirme que a variável de ambiente foi carregada e é usada como usuário e como senha. |
SmtpProtocolException | A porta 465 precisa de SslOnConnect, não de StartTls. |