I am using the .net core 3.1 console application for sending auto-mail to different Email Addresses after sending 4 successful emails It shows Exception
Message: Email sending Failure.
Inner Exception: System.IO.IOException: Unable to read data from the transport connection: The connection was closed.
I have tried all available solutions on stack overflow
My code :
public email
{
Thread.Sleep(10000);
count++;
if (count % 18 == 0)
{
Thread.Sleep(3600 * 1000);
}
try
{
// System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
int tls12 = 3072; // Tls12 is not defined in the SecurityProtocolType enum in CLI/C++ / ToolsVersion="4.0"
// System::Net::ServicePointManager::SecurityProtocol = (SecurityProtocolType)tls12;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
//System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
//shubham .....
string toEmailId = sEmailAddress;
var fromAddress = new MailAddress(From_Email);
var toAddress = new MailAddress(toEmailId);
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
//587
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, Passwd)
};
string messge = MessageBody.ToString();
var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = messge,
IsBodyHtml = true
};
if (cc != null)
{
foreach (string s in cc)
message.CC.Add(s);
message.Bcc.Add("email Id");
}
{
ServicePointManager.ServerCertificateValidationCallback =
delegate (object s, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
smtp.Send(message);
General.WriteToLogFile(sEmailAddress.ToString(), mFolderPath, "Mailsend.txt");
}
}
catch (Exception ex)
{
General.WriteToLogFile(sEmailAddress.ToString(), mFolderPath, "Exception.txt");
General.WriteToLogFile(ex.Message.ToString(), mFolderPath, "Exception.txt");
General.WriteToLogFile(ex.InnerException.ToString(), mFolderPath, "InnerException.txt");
}
}
}