Search code examples
c#.netsmtpoffice365smtpclient

smtpclient.send hangs while trying to send email via office 365


I am using this code to send email using office 365 exchange server.

var server = "smtp.office365.com";
            var port = 587;
            var username = "[email protected]";
            var password = "password";

            var to = "[email protected]";
            var subject = "test message";
            var body = "test message";

            var smtpClient = new SmtpClient(server, port)
            {
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(username, password),
                DeliveryMethod = SmtpDeliveryMethod.Network,
                EnableSsl = true
            };

            var messsage = new MailMessage(username, to, subject, body);

            try
            {
                smtpClient.Send(messsage);
                Console.WriteLine("Mail sent completed");

            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
            }

my code simply hangs at smtpClient.Send(messsage);

I can send email using this account. The account does not have 2FA enabled. I also don't see anyone having a similar issue. Any help would be appreciated.

Thanks Tiklu


Solution

  • After enabling SMTP auth following this process

    https://learn.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission

    we were able to solve the issue

    Thanks Tiklu