使用 SmtpClient 和 MailKit 在 C# (.NET) 中发送电子邮件

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在 C# (.NET) 中发送电子邮件:从 SmtpClient 到 MailKit

发送电子邮件是开发 Web 应用程序、通知服务和企业系统时的关键任务之一。在 .NET 生态系统中,既有内置工具,也有第三方库,它们简化了与 SMTP、SSL/TLS 以及复杂场景的处理。在本文中,我们将详细解析如何使用经典的 SmtpClient 和现代库 MailKit 在 C# 中发送电子邮件。



1. 内置 SmtpClient (System.Net.Mail)

SmtpClient 类在 .NET Framework 和 .NET Core/5+(有一些限制)中可用。它允许您通过任何 SMTP 服务器快速配置邮件发送。



发送电子邮件的基本示例

using System.Net;using System.Net.Mail;

var smtpClient = new SmtpClient("smtp.gmail.com"){ Port = 587, Credentials = new NetworkCredential("your_email@gmail.com", "your_app_password"), EnableSsl = true};

var mailMessage = new MailMessage{ From = new MailAddress("your_email@gmail.com"), Subject = "来自 C# 的测试邮件", Body = "你好!此消息是通过 SmtpClient 发送的。", IsBodyHtml = false};

mailMessage.To.Add("recipient@example.com");

try{ smtpClient.Send(mailMessage); Console.WriteLine("邮件发送成功!");}catch (Exception ex){ Console.WriteLine($"发送错误:{ex.Message}");}

重要提示: 对于 Gmail,您需要 应用密码,而不是普通密码。对于其他服务(Yandex、Mail.ru),请检查 SMTP 设置。



发送带附件的 HTML 邮件

var message = new MailMessage();message.From = new MailAddress("sender@example.com");message.To.Add("user@example.com");message.Subject = "月度报告";message.IsBodyHtml = true;message.Body = "<h2>月度报告</h2><p>附件中有 PDF 文件。</p>";

// 添加附件var attachment = new Attachment(@"C:\\Reports\\report.pdf");message.Attachments.Add(attachment);

using (var client = new SmtpClient("smtp.example.com", 587)){ client.Credentials = new NetworkCredential("login", "password"); client.EnableSsl = true; client.Send(message);}

附件可以是任何类型:图片、文档、压缩包。要从内存发送,请使用 MemoryStream。



2. 异步发送

在现代应用程序中,最好不要阻塞线程。请使用 SendMailAsync:

public async Task SendEmailAsync(){    using var client = new SmtpClient("smtp.example.com", 587);    client.Credentials = new NetworkCredential("login", "password");    client.EnableSsl = true;

var message = new MailMessage("from@example.com", "to@example.com") { Subject = "异步发送", Body = "此邮件是异步发送的。" };

await client.SendMailAsync(message); Console.WriteLine("已异步发送!");}


3. SmtpClient 的问题及替代方案

尽管使用简单,SmtpClient 仍有一些缺点:

  • API 过时(在 .NET 5+ 中已被标记为过时);
  • 对现代身份验证协议(OAuth2)支持不佳;
  • 缺乏对 S/MIME 和高级场景的内置支持。

因此,微软建议使用第三方库,例如 MailKit。



4. MailKit — 用于处理电子邮件的现代库

MailKit 是一个跨平台的开源库。它支持 SMTP、POP3、IMAP、SSL/TLS、异步、OAuth2 等等。



通过 NuGet 安装

\

推荐