SMTP服务器连接失败报错求助:无法理解报错原因及代码排查
Hey there, let's work through that frustrating SMTP connection error you're hitting in C#. The "Service not available, closing transmission channel. The server response was: Unable to connect to SMTP server" message usually points to configuration, authentication, or network blockers—let's break down the most likely fixes step by step:
Common Issues & Fixes
1. Conflict Between UseDefaultCredentials and Credentials
This is a super common gotcha! When you set UseDefaultCredentials = true, the SmtpClient completely ignores the explicit NetworkCredential you've defined. You need to flip that flag to false first before applying your custom credentials:
client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("Alert@domain.com", "your-actual-password");
2. Incorrect SMTP Port & Missing SSL/TLS
Port 25 is often blocked by ISPs, firewalls, or modern email providers (since it's unencrypted by default). Most services use port 587 with TLS encryption, or 465 with SSL. Update your settings to match:
client.Port = 587; // Switch to 465 if your provider uses SSL instead of TLS client.EnableSsl = true; // Critical for secure, allowed connections
3. Verify SMTP Host Address
Double-check that webmail.domain.com is the correct SMTP server provided by your email service. Many providers use smtp.domain.com instead of webmail—confirm this with your email admin or service documentation.
4. Check Network/Firewall Restrictions
Your local firewall, company network, or ISP might be blocking outgoing connections to the SMTP port. Test connectivity first using PowerShell to rule this out:
Test-NetConnection webmail.domain.com -Port 587
If this test fails, you'll need to adjust firewall rules or check with your network team to unblock the port.
5. Validate Account Permissions & Password
Make sure the Alert@domain.com account has permission to send emails via SMTP, and that your password is correct (no typos, expired credentials, or 2FA blocking if enabled).
Modified Working Example
Here's a cleaned-up version of your code with the key fixes applied:
MailMessage objeto_mail = new MailMessage(); SmtpClient client = new SmtpClient(); client.Host = "webmail.domain.com"; // Confirm this address is correct client.Port = 587; client.Timeout = 1000000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; // Fixed credential conflict client.Credentials = new System.Net.NetworkCredential("Alert@domain.com", "your-actual-password"); client.EnableSsl = true; // Added secure connection support // Add your MailMessage details here // objeto_mail.To.Add("recipient@example.com"); // objeto_mail.Subject = "System Alert"; // objeto_mail.Body = "This is a test alert email from C#"; try { client.Send(objeto_mail); Console.WriteLine("Email sent successfully!"); } catch (Exception ex) { Console.WriteLine($"Error sending email: {ex.Message}"); }
内容的提问来源于stack exchange,提问作者Venkatesh

