gpt4 book ai didi

c# - 在 .NET 2.0 中发送电子邮件时出现 "existing connection was forcibly closed"错误

转载 作者:可可西里 更新时间:2023-11-01 10:08:20 25 4
gpt4 key购买 nike

我有 asp.net 网站。我正在通过 SMTPClient 发送电子邮件。有时我会收到此错误:

 InnerException = System.IO.IOException: Unable to read data from the transport connection: 
An existing connection was forcibly closed by the remote host. --->
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.DelegatedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.BufferedReadStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.SmtpReplyReader.ReadLine()
at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response)
at System.Net.Mail.DataStopCommand.Send(SmtpConnection conn)
at System.Net.Mail.SmtpConnection.OnClose(Object sender, EventArgs args)
at System.Net.ClosableStream.Close()
at System.Net.Mail.MailWriter.Close()
at System.Net.Mail.SmtpClient.Send(MailMessage message).

代码:

 SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["smtpserverwwwpo"]);
try
{
NetworkCredential basicCredential =
new NetworkCredential(ConfigurationManager.AppSettings["smtp_user_name"], ConfigurationManager.AppSettings["smtp_password"]);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
}
catch
{
smtpClient.UseDefaultCredentials = true;
}

System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.Subject = subject;
msg.To.Add(new MailAddress(someEmail));
msg.From = new MailAddress(ConfigurationManager.AppSettings["from_email_address"]);
msg.Headers.Add("Content-Type", "text/html");
msg.BodyEncoding = System.Text.Encoding.UTF8;

try{
smtpClient.Send(msg);
}
catch(Exception ex)
{
//write log
}

什么原因会导致呢?

最佳答案

MailMessage 是一次性的。您可以尝试将其包装在 using 语句中。

using(var message = new MailMessage {Subject ="...", Body="..."})
{
message.To.Add("email address");
new SmtpClient().Send(message)
}

关于c# - 在 .NET 2.0 中发送电子邮件时出现 "existing connection was forcibly closed"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8581112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com