We have an email accounts as emailName@companyDomain.in and this is configured in Office365. We want to send an email using emailName@companyDomain.in 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 = "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)
{
}
}
Can you please give any hint about what could be wrong?