c# mailkit smtpclient
时间: 2024-08-26 20:00:20 浏览: 43
在 C# 中,MailKit 是一个流行的开源库,用于发送电子邮件。它提供了一个 SMTPClient 类,这个类允许你通过简单易用的 API 与 Simple Mail Transfer Protocol (SMTP) 服务器交互,从而实现邮件的发送功能。使用 MailKit,你可以创建一个新的 SMTPClient 对象,设置必要的凭据(如主机名、端口、用户名和密码),然后调用其 Send() 方法发送包含邮件内容的消息。
下面是一个基本的示例:
```csharp
using MailKit.Net.Smtp;
using System.IO;
// 创建SMTP客户端实例
var client = new SmtpClient("smtp.example.com", 587);
client.AuthenticationMechanisms.Add(SmtpAuthenticationMethod.XOAUTH2);
// 登录到SMTP服务器
await client.ConnectAsync("smtp.example.com", 587, true); // 使用TLS加密
await client.AuthenticateAsync("your_username", "your_password");
// 构建邮件消息
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Your Name", "your_email@example.com"));
message.To.Add(new MailboxAddress("Recipient's Name", "recipient_email@example.com"));
message.Subject = "Test Email";
message.Body = new TextPart("plain") { Text = "This is a test email." };
// 发送邮件
await client.SendAsync(message);
await client.DisconnectAsync(true); // 断开连接
// 关闭资源
client.Dispose();
```