方法1:System.Net.Mail.SmtpClient
標準搭載ですが、新規開発では非推奨とされています。587番ポートで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);
方法2:MailKit(推奨)
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);
どちらを使うべき?
新しいコードではすべてMailKitを使いましょう。どのポートでもTLSを正しく扱い、キャンセル対応の完全なasyncで、活発にメンテナンスされています。SmtpClientは、触りたくない既存のコードにだけ残しましょう。
トラブルシューティング
| 症状 | 対処 |
|---|---|
Authentication failed | 環境変数が読み込まれ、usernameとpasswordの両方に使われているか確認してください。 |
SmtpProtocolException | 465番ポートにはStartTlsではなくSslOnConnectが必要です。 |