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

Oxy*_*gen 8 c# smtpclient office365

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

 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)
        {
           
        }
    }
Run Code Online (Sandbox Code Playgroud)

您能给出任何可能出现问题的提示吗?

小智 16

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

{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                      | SecurityProtocolType.Tls11
                                      | SecurityProtocolType.Tls12;
}
Run Code Online (Sandbox Code Playgroud)

  • 太感谢了!它解决了我随机收到 net_io_connectoinclosure 错误的问题。 (2认同)