使用 C# 连接到 SMTP 服务器

简单邮件传输协议 (SMTP) 是最常用的电子邮件协议,用于处理从客户端应用程序向电子邮件服务器发送电子邮件消息。在各种情况下,电子邮件客户端在 .NET 应用程序中实现,以便通过 SMTP 发送电子邮件。对于这种情况,本文介绍了如何使用 C# 以编程方式连接到 SMTP 服务器。此外,代码示例演示了如何在连接建立后通过 SMTP 客户端发送电子邮件。

C# API 连接 SMTP 服务器

Aspose.Email for .NET 是一个 C# API,旨在创建强大的电子邮件客户端应用程序。该 API 可以在几行代码内非常轻松地执行复杂的电子邮件操作。此外,它还允许您通过 SOCKS 和 HTTP 代理服务器连接 SMTP 服务器。您可以 下载 API 的 DLL 或使用 NuGet 安装它。

PM> Install-Package Aspose.Email

使用 C# 连接到 SMTP 服务器

在连接到 SMTP 服务器之前,您需要了解以下事项。

  • 用户名
  • 密码
  • 港口

拥有它们后,您可以使用以下步骤配置 SMTP 客户端。

以下代码示例展示了如何在 C# 中为 SMTP 连接设置 API。

// 如需完整的示例和数据文件,请访问 https://github.com/aspose-email/Aspose.Email-for-.NET
SmtpClient client = new SmtpClient("smtp.gmail.com");

// 设置用户名、密码、端口和安全选项
client.Username = "your.email@gmail.com";
client.Password = "your.password";
client.Port = 587;
client.SecurityOptions = SecurityOptions.SSLExplicit;

配置 API 后,您可以使用以下选项之一连接到 SMTP 服务器。

在 C# 中通过 SOCKS 代理服务器连接到 SMTP

Aspose.Email 支持 SOCKS 代理协议的版本 4、4a 和 5。以下是使用 Aspose.Email for .NET 通过 SOCKS 代理服务器连接到 SMTP 服务器的步骤。

以下代码示例显示了如何使用 C# 通过 SOCKS 代理连接到 SMTP 服务器。

// 如需完整的示例和数据文件,请访问 https://github.com/aspose-email/Aspose.Email-for-.NET
SmtpClient client = new SmtpClient("smtp.domain.com", "username", "password");
client.SecurityOptions = SecurityOptions.SSLImplicit;
string proxyAddress = "192.168.203.142"; // proxy address
int proxyPort = 1080; // proxy port
SocksProxy proxy = new SocksProxy(proxyAddress, proxyPort, SocksVersion.SocksV5);
client.Proxy = proxy;
client.Send(new MailMessage("sender@domain.com", "receiver@domain.com", "Sending Email via proxy", "Implement socks proxy protocol for versions 4, 4a, 5 (only Username/Password authentication)"));

通过 HTTP 代理服务器连接到 SMTP 服务器

以下是通过 HTTP 代理服务器连接到 SMTP 服务器的步骤。

以下代码示例显示了如何通过 HTTP 代理服务器连接到 SMTP 服务器。

// 如需完整的示例和数据文件,请访问 https://github.com/aspose-email/Aspose.Email-for-.NET
HttpProxy proxy = new HttpProxy("18.222.124.59", 8080);
using (SmtpClient client = new SmtpClient("host", 587, "username", "password"))
{
    client.Proxy = proxy;
    client.Send(new MailMessage(
        "from@domain.com",
        "to@domain.com",
        "NETWORKNET-34226 - " + Guid.NewGuid().ToString(),
        "NETWORKNET-34226 Implement socks proxy protocol for versions 4, 4a, 5 (only Username/Password authentication)"));
}

获取免费 API 许可证

您可以通过获得临时许可证 来免费尝试使用 Aspose.Email for .NET。

结论

在本文中,您学习了如何使用 C# 连接到 SMTP 服务器。此外,分步指南和代码示例展示了如何通过 SOCKS 和 HTTP 代理服务器连接到 SMTP 服务器。您可以使用 文档 探索有关 C# 电子邮件 API 的更多信息。

也可以看看