SmtpClient 클래스

정의

애플리케이션에서 SMTP(Simple Mail Transfer Protocol)를 사용하여 이메일을 보낼 수 있도록 합니다. 일부 플랫폼에서는 SmtpClient 형식이 사용되지 않으며 다른 플랫폼에서는 권장되지 않습니다. 자세한 내용은 설명 섹션을 참조하세요.

public ref class SmtpClient : IDisposable
public ref class SmtpClient
public class SmtpClient : IDisposable
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public class SmtpClient : IDisposable
public class SmtpClient
type SmtpClient = class
    interface IDisposable
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
type SmtpClient = class
    interface IDisposable
type SmtpClient = class
Public Class SmtpClient
Implements IDisposable
Public Class SmtpClient
상속
SmtpClient
특성
구현

예제

다음 코드 예제에서는 전자 메일 메시지를 비동기적으로 보내는 방법을 보여 줍니다.

#using <System.dll>
using namespace System;
using namespace System::Net;
using namespace System::Net::Mail;
using namespace System::Net::Mime;
using namespace System::Threading;
using namespace System::ComponentModel;

static bool mailSent;

static void SendCompletedCallback(Object^ sender, AsyncCompletedEventArgs^ e)
{
    // Get the unique identifier for this asynchronous 
    // operation.
    String^ token = (String^) e->UserState;

    if (e->Cancelled)
    {
        Console::WriteLine("[{0}] Send canceled.", token);
    }
    if (e->Error != nullptr)
    {
        Console::WriteLine("[{0}] {1}", token, 
            e->Error->ToString());
    } else
    {
        Console::WriteLine("Message sent.");
    }
    mailSent = true;
}

int main(array<String^>^ args)
{
    if (args->Length > 1)
    {
        // Command-line argument must be the SMTP host.
        SmtpClient^ client = gcnew SmtpClient(args[1]);
        // Specify the email sender.
        // Create a mailing address that includes a UTF8 
        // character in the display name.
        MailAddress^ from = gcnew MailAddress("jane@contoso.com",
            "Jane " + (wchar_t)0xD8 + " Clayton",
            System::Text::Encoding::UTF8);
        // Set destinations for the email message.
        MailAddress^ to = gcnew MailAddress("ben@contoso.com");
        // Specify the message content.
        MailMessage^ message = gcnew MailMessage(from, to);
        message->Body = "This is a test email message sent" +
            " by an application. ";
        // Include some non-ASCII characters in body and 
        // subject.
        String^ someArrows = gcnew String(gcnew array<wchar_t>{L'\u2190', 
            L'\u2191', L'\u2192', L'\u2193'});
        message->Body += Environment::NewLine + someArrows;
        message->BodyEncoding = System::Text::Encoding::UTF8;
        message->Subject = "test message 1" + someArrows;
        message->SubjectEncoding = System::Text::Encoding::UTF8;
        // Set the method that is called back when the send
        // operation ends.
        client->SendCompleted += gcnew
            SendCompletedEventHandler(SendCompletedCallback);
        // The userState can be any object that allows your 
        // callback method to identify this send operation.
        // For this example, the userToken is a string constant.
        String^ userState = "test message1";
        client->SendAsync(message, userState);
        Console::WriteLine("Sending message... press c to" +
            " cancel mail. Press any other key to exit.");
        String^ answer = Console::ReadLine();
        // If the user canceled the send, and mail hasn't been 
        // sent yet,then cancel the pending operation.
        if (answer->ToLower()->StartsWith("c") && mailSent == false)
        {
            client->SendAsyncCancel();
        }
        // Clean up.
        delete message;
        client = nullptr;
        Console::WriteLine("Goodbye.");
    }
    else
    {
        Console::WriteLine("Please give SMTP server name!");
    }
}

using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace Examples.SmtpExamples.Async
{
    public class SimpleAsynchronousExample
    {
        static bool mailSent = false;
        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
             String token = (string) e.UserState;

            if (e.Cancelled)
            {
                 Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                 Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            } else
            {
                Console.WriteLine("Message sent.");
            }
            mailSent = true;
        }
        public static void Main(string[] args)
        {
            // Command-line argument must be the SMTP host.
            SmtpClient client = new SmtpClient(args[0]);
            // Specify the email sender.
            // Create a mailing address that includes a UTF8 character
            // in the display name.
            MailAddress from = new MailAddress("jane@contoso.com",
               "Jane " + (char)0xD8+ " Clayton",
            System.Text.Encoding.UTF8);
            // Set destinations for the email message.
            MailAddress to = new MailAddress("ben@contoso.com");
            // Specify the message content.
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test email message sent by an application. ";
            // Include some non-ASCII characters in body and subject.
            string someArrows = new string(new char[] {'\u2190', '\u2191', '\u2192', '\u2193'});
            message.Body += Environment.NewLine + someArrows;
            message.BodyEncoding =  System.Text.Encoding.UTF8;
            message.Subject = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new
            SendCompletedEventHandler(SendCompletedCallback);
            // The userState can be any object that allows your callback
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";
            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();
            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
    }
}

Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
Imports System.Threading
Imports System.ComponentModel

Namespace Examples.SmtpExamples.Async
    Public Class SimpleAsynchronousExample
        Private Shared mailSent As Boolean = False
        Private Shared Sub SendCompletedCallback(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
            ' Get the unique identifier for this asynchronous operation.
            Dim token As String = CStr(e.UserState)

            If e.Cancelled Then
                Console.WriteLine("[{0}] Send canceled.", token)
            End If
            If e.Error IsNot Nothing Then
                Console.WriteLine("[{0}] {1}", token, e.Error.ToString())
            Else
                Console.WriteLine("Message sent.")
            End If
            mailSent = True
        End Sub
        Public Shared Sub Main(ByVal args() As String)
            ' Command line argument must the SMTP host.
            Dim client As New SmtpClient(args(0))
            ' Specify the email sender.
            ' Create a mailing address that includes a UTF8 character
            ' in the display name.
            Dim mailFrom As New MailAddress("jane@contoso.com", "Jane " & ChrW(&HD8) & " Clayton", System.Text.Encoding.UTF8)
            ' Set destinations for the email message.
            Dim mailTo As New MailAddress("ben@contoso.com")
            ' Specify the message content.
            Dim message As New MailMessage(mailFrom, mailTo)
            message.Body = "This is a test email message sent by an application. "
            ' Include some non-ASCII characters in body and subject.
            Dim someArrows As New String(New Char() {ChrW(&H2190), ChrW(&H2191), ChrW(&H2192), ChrW(&H2193)})
            message.Body += Environment.NewLine & someArrows
            message.BodyEncoding = System.Text.Encoding.UTF8
            message.Subject = "test message 1" & someArrows
            message.SubjectEncoding = System.Text.Encoding.UTF8
            ' Set the method that is called back when the send operation ends.
            AddHandler client.SendCompleted, AddressOf SendCompletedCallback
            ' The userState can be any object that allows your callback 
            ' method to identify this send operation.
            ' For this example, the userToken is a string constant.
            Dim userState As String = "test message1"
            client.SendAsync(message, userState)
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.")
            Dim answer As String = Console.ReadLine()
            ' If the user canceled the send, and mail hasn't been sent yet,
            ' then cancel the pending operation.
            If answer.StartsWith("c") AndAlso mailSent = False Then
                client.SendAsyncCancel()
            End If
            ' Clean up.
            message.Dispose()
            Console.WriteLine("Goodbye.")
        End Sub
    End Class
End Namespace

설명

클래스는 SmtpClient 배달을 위해 SMTP 서버로 전자 메일을 보내는 데 사용됩니다. SMTP 프로토콜은 RFC 2821에서 정의되며 에서 https://www.ietf.org사용할 수 있습니다.

중요

많은 최신 프로토콜을 SmtpClient 지원하지 않으므로 새 개발에 SmtpClient 클래스를 사용하지 않는 것이 좋습니다. 대신 MailKit 또는 다른 라이브러리를 사용합니다. 자세한 내용은 GitHub에서 SmtpClient를 사용하면 안 됨 을 참조하세요.

클래스는 SmtpClient Xamarin에서 사용되지 않습니다. 단,

  • .NET Standard 2.0 이상 버전에 포함되므로 해당 버전을 지원하는 모든 .NET 구현의 일부여야 합니다.
  • 존재하며 .NET Framework 4에서 .NET Framework 4.8까지 사용할 수 있습니다.
  • .NET Core에서 사용할 수 있지만 사용하지 않는 것이 좋습니다.

다음 표에 표시된 클래스는 를 사용하여 SmtpClient보낼 수 있는 전자 메일 메시지를 생성하는 데 사용됩니다.

클래스 설명
Attachment 파일 첨부 파일을 나타냅니다. 이 클래스를 사용하면 파일, 스트림 또는 텍스트를 전자 메일 메시지에 첨부할 수 있습니다.
MailAddress 보낸 사람과 받는 사람의 이메일 주소를 나타냅니다.
MailMessage 전자 메일 메시지를 나타냅니다.

을 사용하여 SmtpClient전자 메일 메시지를 생성하고 보내려면 다음 정보를 지정해야 합니다.

  • 전자 메일을 보내는 데 사용하는 SMTP 호스트 서버입니다. HostPort 속성을 참조하세요.

  • SMTP 서버에서 필요한 경우 인증을 위한 자격 증명입니다. Credentials 속성을 참조하세요.

  • 보낸 사람의 전자 메일 주소입니다. 매개 변수를 Send 사용하는 및 SendAsync 메서드를 from 참조하세요. 속성도 MailMessage.From 참조하세요.

  • 받는 사람의 이메일 주소 또는 주소입니다. 매개 변수를 Send 사용하는 및 SendAsync 메서드를 recipient 참조하세요. 속성도 MailMessage.To 참조하세요.

  • 메시지 내용 매개 변수를 Send 사용하는 및 SendAsync 메서드를 body 참조하세요. 속성도 MailMessage.Body 참조하세요.

전자 메일 메시지에 첨부 파일을 포함하려면 먼저 클래스를 사용하여 Attachment 첨부 파일을 만든 다음 속성을 사용하여 MailMessage.Attachments 메시지에 추가합니다. 받는 사람이 사용하는 전자 메일 판독기 및 첨부 파일의 파일 형식에 따라 일부 받는 사람이 첨부 파일을 읽지 못할 수 있습니다. 원래 형식으로 첨부 파일을 표시할 수 없는 클라이언트의 경우 속성을 사용하여 MailMessage.AlternateViews 대체 보기를 지정할 수 있습니다.

.NET framework에서 애플리케이션을 사용할 수 있습니다 또는 컴퓨터 구성 파일을 지정 하려면 모든 호스트, 포트 및 자격 증명 값을 기본 SmtpClient 개체입니다. 자세한 내용은 mailSettings> 요소(네트워크 설정)를 참조<하세요. .NET Core는 기본값 설정을 지원하지 않습니다. 해결 방법으로 관련 속성을 SmtpClient 직접 설정해야 합니다.

전자 메일이 SMTP 서버로 전송될 때까지 기다리는 동안 전자 메일 메시지를 보내고 차단하려면 동기 Send 메서드 중 하나를 사용합니다. 전자 메일이 전송되는 동안 프로그램의 기본 스레드가 계속 실행되도록 하려면 비동 SendAsync 기 메서드 중 하나를 사용합니다. 작업이 SendCompleted 완료되면 이벤트가 발생 SendAsync 합니다. 이 이벤트를 수신하려면 에 대리SendCompleted자를 SendCompletedEventHandler 추가해야 합니다. 대리자는 SendCompletedEventHandler 이벤트 알림을 SendCompleted 처리하는 콜백 메서드를 참조해야 합니다. 비동기 전자 메일 전송을 취소하려면 메서드를 SendAsyncCancel 사용합니다.

참고

전자 메일 전송이 진행 중이고 또는 Send 를 다시 호출 SendAsync 하면 을 InvalidOperationException받게 됩니다.

현재 인스턴스에서 연결 된 SmtpClient 애플리케이션 같은 SMTP 서버에 여러 메시지를 보낼 경우 SMTP 서버에는 클래스를 다시 사용할 수 있습니다. 이는 인증 또는 암호화를 사용하여 SMTP 서버에 대한 연결을 설정하는 경우에 특히 유용합니다. TLS 세션을 인증하고 설정하는 프로세스는 비용이 많이 들 수 있습니다. 동일한 SMTP 서버에 대량의 이메일을 보낼 때 각 메시지에 대한 연결을 다시 설정해야 하는 요구 사항은 성능에 큰 영향을 미칠 수 있습니다. 전자 메일 상태 업데이트, 뉴스레터 배포, 전송 또는 전자 메일 경고는 대규모 전자 메일 애플리케이션의 여러 가지가 있습니다. 또한 많은 전자 메일 클라이언트 애플리케이션 사용자 SMTP 서버에 연결 되 면 나중에 전송 되는 여러 전자 메일 메시지를 구성할 수 있는 오프 라인 모드를 지원 합니다. 일반적으로 전자 메일 클라이언트는 모든 SMTP 메시지를 특정 SMTP 서버(인터넷 서비스 공급자가 제공)로 보낸 다음 이 이메일을 다른 SMTP 서버로 전달하는 것이 일반적입니다.

클래스 구현은 SmtpClient 동일한 서버에 대한 모든 메시지에 대한 연결을 다시 설정하는 오버헤드를 방지할 수 있도록 SMTP 연결을 풀링합니다. 애플리케이션 수 다시 사용 하 여 동일한 SmtpClient 여러 SMTP 서버와 같은 SMTP 서버에 많은 다른 전자 메일을 보낼 개체입니다. 결과적으로 애플리케이션이 완료 되 면 확인할 방법은 없으며를 사용 하는 SmtpClient 개체 정리 해야 합니다.

SMTP 세션이 완료되고 클라이언트가 연결을 종료하려는 경우 더 이상 보낼 메시지가 없음을 나타내기 위해 QUIT 메시지를 서버로 보내야 합니다. 이렇게 하면 서버가 클라이언트에서 연결과 연결된 리소스를 해제하고 클라이언트에서 보낸 메시지를 처리할 수 있습니다.

합니다 SmtpClient 클래스에 없습니다 Finalize 메서드를 호출 하는 애플리케이션 Dispose 명시적으로 리소스를 확보 합니다. 메서드는 Dispose 속성에 지정된 Host SMTP 서버에 설정된 모든 연결을 반복하고 QUIT 메시지를 보낸 다음 TCP 연결을 정상적으로 종료합니다. 또한 메서드는 Dispose 에서 사용하는 Socket 관리되지 않는 리소스를 해제하고 관리되는 리소스를 선택적으로 삭제합니다.

Dispose 사용을 마치면 SmtpClient를 호출합니다. Dispose 메서드를 사용하면 SmtpClient를 사용할 수 없게 됩니다. 호출한 후 Dispose에 대 한 모든 참조를 해제 해야 합니다 SmtpClient 가비지 수집기에서 메모리를 회수할 수 있도록 하는 SmtpClient 차지한 합니다.

생성자

SmtpClient()

구성 파일 설정을 사용하여 SmtpClient 클래스의 새 인스턴스를 초기화합니다.

SmtpClient(String)

지정된 SMTP 서버를 사용하여 이메일을 보내는 SmtpClient 클래스의 새 인스턴스를 초기화합니다.

SmtpClient(String, Int32)

지정된 SMTP 서버 및 포트를 사용하여 이메일을 보내는 SmtpClient 클래스의 새 인스턴스를 초기화합니다.

속성

ClientCertificates

SSL(Secure Sockets Layer) 연결을 설정하는 데 사용할 인증서를 지정합니다.

Credentials

보낸 사람을 인증하는 데 사용되는 자격 증명을 가져오거나 설정합니다.

DeliveryFormat

SmtpClient에서 이메일을 보내는 데 사용하는 배달 형식을 가져오거나 설정합니다.

DeliveryMethod

보내는 전자 메일 메시지의 처리 방법을 지정합니다.

EnableSsl

SmtpClient에서 SSL(Secure Sockets Layer)을 사용하여 연결을 암호화할지 여부를 지정합니다.

Host

SMTP 트랜잭션에 사용되는 호스트의 이름 또는 IP 주소를 가져오거나 설정합니다.

PickupDirectoryLocation

애플리케이션이 로컬 SMTP 서버에서 처리할 메일 메시지를 저장하는 폴더를 가져오거나 설정합니다.

Port

SMTP 트랜잭션에 사용되는 포트를 가져오거나 설정합니다.

ServicePoint

이메일 메시지를 전송하는 데 사용되는 네트워크 연결을 가져옵니다.

TargetName

확장 보호를 사용하는 경우 인증에 사용할 SPN(서비스 공급자 이름)을 가져오거나 설정합니다.

Timeout

동기 Send 호출이 완료되어야 하는 제한 시간을 지정하는 값을 가져오거나 설정합니다.

UseDefaultCredentials

요청에 Boolean을 보낼지 여부를 제어하는 DefaultCredentials 값을 가져오거나 설정합니다.

메서드

Dispose()

QUIT 메시지를 SMTP 서버에 보내고, TCP 연결을 정상적으로 종료하고, SmtpClient 클래스의 현재 인스턴스가 사용하는 모든 리소스를 해제합니다.

Dispose(Boolean)

QUIT 메시지를 SMTP 서버에 보내고, TCP 연결을 정상적으로 종료하고, SmtpClient 클래스의 현재 인스턴스가 사용하는 모든 리소스를 해제하고, 관리되는 리소스를 선택적으로 삭제합니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
OnSendCompleted(AsyncCompletedEventArgs)

SendCompleted 이벤트를 발생시킵니다.

Send(MailMessage)

배달용 SMTP 서버로 지정된 메시지를 보냅니다.

Send(String, String, String, String)

배달용 SMTP 서버로 지정된 이메일 메시지를 보냅니다. 메시지의 보낸 사람, 받는 사람, 제목 및 메시지 본문은 String 개체를 사용하여 지정됩니다.

SendAsync(MailMessage, Object)

배달용 SMTP 서버로 지정된 이메일 메시지를 보냅니다. 이 메서드는 호출 스레드를 차단하지 않으며 작업이 완료될 때 호출된 메서드에 호출자가 개체를 전달하도록 허용합니다.

SendAsync(String, String, String, String, Object)

배달용 SMTP 서버로 이메일 메시지를 보냅니다. 메시지의 보낸 사람, 받는 사람, 제목 및 메시지 본문은 String 개체를 사용하여 지정됩니다. 이 메서드는 호출 스레드를 차단하지 않으며 작업이 완료될 때 호출된 메서드에 호출자가 개체를 전달하도록 허용합니다.

SendAsyncCancel()

이메일 메시지를 보내기 위한 비동기 작업을 취소합니다.

SendMailAsync(MailMessage)

배달용 SMTP 서버로 지정된 전자 메일 메시지를 비동기 작업으로 보냅니다.

SendMailAsync(MailMessage, CancellationToken)

배달용 SMTP 서버로 지정된 전자 메일 메시지를 비동기 작업으로 보냅니다.

SendMailAsync(String, String, String, String)

배달용 SMTP 서버로 지정된 전자 메일 메시지를 비동기 작업으로 보냅니다. 메시지의 보낸 사람, 받는 사람, 제목 및 메시지 본문은 String 개체를 사용하여 지정됩니다.

SendMailAsync(String, String, String, String, CancellationToken)

지정된 보낸 사람, 받는 사람, 제목 및 본문 문자열을 사용하여 비동기 작업으로 배달하기 위해 지정된 메시지를 SMTP 서버에 보냅니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

이벤트

SendCompleted

비동기 이메일 보내기 작업이 완료되었을 때 발생합니다.

적용 대상

추가 정보