C#

[C#] 어느날 갑자기 Smtp 메일 전송이 안된다

오즈마스터 2022. 2. 11. 17:46

오피스365 Exchange 계정을 통해 C# 으로 .Net SmtpClient 클래스를 통해 메일을 보내는 기능을 구현해서 1년 넘게 잘 쓰고 있다가, 최근에 점점 실패 횟수가 잦더니 이제는 아예 기능 자체가 먹통이 되어 버렸다.

원인은 .Net 의 SmtpClient 라이브러리가 deprecated 된 탓이고, 자세한 이유는 최근의 여러 보안 프로토콜(가령 StartTLS)을 지원하지 못한 탓이란다.

 

We don't recommend that you use the SmtpClient class for new development because SmtpClient doesn't support many modern protocols. Use MailKit or other libraries instead. For more information, see SmtpClient shouldn't be used on GitHub.

링크: https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=net-6.0 

 

SmtpClient Class (System.Net.Mail)

Allows applications to send email by using the Simple Mail Transfer Protocol (SMTP). The SmtpClient type is obsolete on some platforms and not recommended on others; for more information, see the Remarks section.

docs.microsoft.com

 

해결법은 MailKit 라는 공개된 라이브러리를 사용하라고 한다. (이래도 되나 싶어서 눈을 의심했음. 그래도 유명한 라이브러리니까  곧 수긍함.)

NuGet 을 통해 MailKit 를 검색해 설치하고, 바로 샘플 코드를 테스트 해봤더니 잘 된다.

            string idSender = "sender@domain.com";
            string pwSender = "xhdtlsqhdks";
            string mailTo = "receiver@domain.com";
            string subject = "Mail send test";
            string body = "<H2>Test</H2><H3>Hello World</H3><br/>";

            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("", idSender));
            message.To.Add(new MailboxAddress("", mailTo));
            message.Subject = subject;

            var bodyBuilder = new BodyBuilder();
            bodyBuilder.HtmlBody = body;
            //bodyBuilder.TextBody = "This is some plain text";
            message.Body = bodyBuilder.ToMessageBody();
            //message.Body = new TextPart("plain") { Text = body };

            using (var client = new SmtpClient())
            {
                client.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);
                client.Authenticate(idSender, pwSender);
                client.Send(message);
                client.Disconnect(true);
            }

 

결정적인 단서를 찾게해준 아래 링크에 감사한다.

http://daplus.net/c-smtpexception-%EC%A0%84%EC%86%A1-%EC%97%B0%EA%B2%B0%EC%97%90%EC%84%9C-%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%A5%BC-%EC%9D%BD%EC%9D%84-%EC%88%98-%EC%97%86%EC%9D%8C-net_io_connectionclosed/