Cách 1: System.Net.Mail.SmtpClient
Có sẵn, nhưng bị đánh dấu lỗi thời cho phát triển mới — dùng port 587 với 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);
Cách 2: MailKit (khuyến nghị)
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);
Nên dùng cái nào?
Dùng MailKit cho mọi code mới — nó xử lý TLS đúng trên mọi port, async hoàn toàn có hỗ trợ hủy và được bảo trì tích cực. Chỉ giữ SmtpClient trong code cũ bạn không muốn đụng tới.
Khắc phục sự cố
| Triệu chứng | Cách sửa |
|---|---|
Authentication failed | Xác nhận biến môi trường đã được nạp và dùng cho cả username lẫn password. |
SmtpProtocolException | Port 465 cần SslOnConnect, không phải StartTls. |