我見過很多從c#代碼發送郵件的例子,我遵循最流行的使用System.Net.Mail.SmtpClient
的方法。我能夠首次發送郵件,但之後會發出錯誤說明連接請求發生在已連接的套接字上。C#發送郵件時出錯:連接請求是在已經連接的套接字上進行的
我使用下面的代碼來發送郵件:
using (MailMessage mail = new MailMessage())
{
using (SmtpClient mailer = new SmtpClient("smtp.server.com"))
{
Console.Write("Sending mails...");
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "test-subject";
mail.Body = "test-body";
mailer.Port = 25;
mailer.Credentials = new System.Net.NetworkCredential("[email protected]", "from-password");
mailer.EnableSsl = true;
try
{
mailer.Send(mail);
Console.WriteLine("Mail sent");
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\rCannot send mail, an error occured : {0}", e);
Console.ResetColor();
}
}
}
錯誤消息:
Cannot send mail, an error occured : System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connect request was made on an already connected socket 200.200.200.200:25
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at TestApp.Program.Main(String[] args) in D:\Desktop\TestApp\TestApp\Program.cs:line 290
兩個MailMessage
和內部using
條款正如你所看到的,我一直實例SmptClient
這樣如果發生任何錯誤,連接將自動關閉。但它在正確引導後第一次發送郵件,之後所有其他嘗試都失敗。
SMTP服務器位於代理之後,防火牆客戶端正在我的系統上運行。代理不是一個問題,在我看來這裏。
代碼中是否有錯誤?我怎樣才能使它工作?
我已經嘗試使用Outlook API,但在發送每封郵件之前需要用戶進行身份驗證。我不想要這種行爲。 PS:我刪除了一些細節,如IP地址和服務器名稱,在這種情況下無關緊要。
在此先感謝:)
您正在使用哪種版本的DotNet Framework? – Steve
.NET Framework 3.5.1 – ruhil