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

We have an email accounts as [email protected] and this is configured in Office365. We want to send an email using [email protected] from C#. Below code sometimes work and sometimes not (most of the times not working). Giving Error as "Unable to read data from the transport connection: net_io_connectionclosed". Code is

 public static void SendEmail(string toEmailId, string subject, string mailMessage)
    {
        string fromEmail = "[email protected]";
        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)
        {
           
        }
    }

Can you please give any hint about what could be wrong?



Solution 1:[1]

Adding this code before creating the smtp client worked for me.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Elikill58