如何解决无法从传输连接读取数据:使用 SMTPClient 发送电子邮件时出现 net_io_connectionclosed 错误

How to resolve Unable to read data from the transport connection: net_io_connectionclosed error while sending email using SMTPClient

我们有一个电子邮件帐户 emailName@companyDomain.in,这是在 Office365 中配置的。我们想在 C# 中使用 emailName@companyDomain.in 发送电子邮件。 下面的代码有时有效,有时无效(大部分时间无效)。给出错误 “无法从传输连接读取数据:net_io_connectionclosed”。代码是

 public static void SendEmail(string toEmailId, string subject, string mailMessage)
    {
        string fromEmail = "emailName@companyDomain.in";
        MailMessage msg = new MailMessage();
        msg.To.Add(toEmailId);
        msg.From = new MailAddress(fromEmail, "Sender Name");
        msg.Subject = subject;
        msg.Body = mailMessage;
        msg.IsBodyHtml = true;

        SmtpClient client = new SmtpClient();
        client.UseDefaultCredentials = false; // Tried by commenting this too
        client.Credentials = new System.Net.NetworkCredential(fromEmail, "password");
        client.Port = 587; // Tried port number 25
        client.Host = "smtp.office365.com";
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.TargetName = "STARTTLS/smtp.office365.com";
        client.EnableSsl = true;
        try
        {
            client.Send(msg);
        }
        catch (Exception ex)
        {
           
        }
    }

能否请您给出任何可能出错的提示?

在创建 smtp 客户端之前添加这段代码对我有用。

{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                      | SecurityProtocolType.Tls11
                                      | SecurityProtocolType.Tls12;
}