在C#中實現SMTP身份驗證需要使用System.Net.Mail命名空間中的SmtpClient類。以下是一個簡單的示例代碼:
using System;
using System.Net;
using System.Net.Mail;
class Program
{
static void Main()
{
string smtpServer = "smtp.example.com";
int port = 587; // SMTP端口
string userName = "your_username";
string password = "your_password";
string fromAddress = "from@example.com";
string toAddress = "to@example.com";
using (SmtpClient client = new SmtpClient(smtpServer, port))
{
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(userName, password);
client.EnableSsl = true;
MailMessage message = new MailMessage(fromAddress, toAddress);
message.Subject = "Test Email";
message.Body = "This is a test email.";
try
{
client.Send(message);
Console.WriteLine("Email sent successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Failed to send email. Error message: " + ex.Message);
}
}
}
}
在這段代碼中,我們首先創建一個SmtpClient對象,并設置SMTP服務器、端口、用戶名和密碼。然后創建一個MailMessage對象,并設置郵件主題和內容。最后調用SmtpClient的Send方法發送郵件。
請注意,有些SMTP服務器可能需要打開SMTP身份驗證功能才能正常發送郵件。另外,為了保證郵件的安全性,建議使用SSL加密連接SMTP服務器。