[C#] SMTP 서비스를 이용해 이메일 발송하기

닷넷 환경에서의 이메일 발송은 MailMessage 클래스를 사용합니다.

따라서 System.Net.Mail 네임 스페이스를 필요로 합니다.

코드에 포함시켜야 합니다.

기본 코드는 다음과 같습니다.


로컬 SMTP 서버를 이용해 메일 발송하기

using System.Net.Mail

try
{
  MailMessage message = new MailMessage();

  message.From = new MailAddress("발송자이름" + "<" + "email@domain.com>");
  message.To.Add("emailaddress@sender.com");
  message.To.Add("emailaddress@sendor.co.kr");

  string subject = "메일발송 테스트";
  message.Subject = subject;
  message.IsBodyHtml = true;
  string content = "<html><head></head><body><span>HTML 테스트 이메일</span></body></html>";
  message.Body = content;

  SmtpClient client = new SmtpClient("localhost");
  client.Port = 587;
  client.Send(message);

  if(message != null){message.Dispose();message = null;}
  if(client != null){client.Dispose();client = null;}
}
catch (Exception ex)
{
	Response.Write(ex.ToString());
}

MailMessage 객체를 생성한 후 각각의 속성에 값들을 채워 넣어야 합니다.

1. 발송자 정보를 표시합니다.

MailMessage.From = new MailAddress("이메일주소");

.From 속성에 이메일 주소가 아닌 발송자 이름으로 표시하려면 "발송자이름<email@domain.com>" 형식으로 꺽쇠로 이메일 주소를 감싸서 이름을 표시하면 "발송자이름"으로 발송자가 표시됩니다.

발송자(From) 속성은 메일 주소 객체로 추가해야 합니다.

new MailAddress("메일주소") 형식으로 새 메일 주소 객체를 만들어서 From 속성에 적용합니다.

2. 수신자 이메일 주소를 추가합니다.

MailMessage.To.Add("이메일주소");

로 추가합니다. 여러 개의 이메일 주소를 추가할 수 있습니다.

3. 제목과 내용을 작성합니다.

MailMessage.Subject = "메일 제목";

MailMessage.Body = "<html><head></head><body><span>HTML내용</span></body></html>";

HTML을 지원하지 않은 메일 클라이언트에서 HTML 내용 대신 텍스트 내용만 표시할 수 있도록 하려면 다음처럼 대체 텍스트를 MailMessage.AlternativeViews 속성에 추가해야 합니다.

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(content, new ContentType("text/html")); message.AlternateViews.Add(htmlView);

4. SMTP 클라이언트 객체를 생성합니다.

포트는 587 포트로 해야 합니다. 25번 포트는 보안상 국내 포털 메일과 대부분 서비스에서 막혀있기 때문에 반드시 587 포트를 사용해야 합니다.

SmtpClient client = new SmtpClient("localhost");
client.Port = 587;

윈도 서버의 SMTP 서비스 설정 방법은 다음 글을 참고하면 됩니다.

> 메일발송을 위한 윈도우 서버 로컬 SMTP 서버 설정하기

5. 메일을 발송합니다.


client.Send(message);


외부 SMTP 서버를 이용해서 메일 발송하기

포털 메일이나 SMTP 서비스를 제공하는 웹 메일 서비스를 이용해서 메일을 발송할 수 있습니다.

로컬 SMTP 서비스와 발송 방법은 동일하며, 발송 SMTP 서버와 발송 포트, 그리고 발송 이메일 주소만 변경하면 됩니다.

카페24의 웹 메일 서비스에서 제공하는 SMTP 서버를 이용해 메일을 발송하는 코드는 다음과 같습니다.

using System.Net.Mail

try
{
  MailMessage message = new MailMessage();

  message.From = new MailAddress("발송자이름" + "<" + "email@domain.com>");
  message.To.Add("emailaddress@sender.com");
  message.To.Add("emailaddress@sendor.co.kr");

  string subject = "메일발송 테스트";
  message.Subject = subject;
  message.IsBodyHtml = true;
  string content = "<html><head></head><body><span>HTML 테스트 이메일</span></body></html>";
  message.Body = content;

  SmtpClient client = new SmtpClient("smtp.cafe24.com", 587)
  {
    Credentials = new NetworkCredential("emailaddress@domain.com", "이메일패스워드"),
    EnableSsl = true
  };
  client.Port = 587;
  client.Send(message);

  if(message != null){message.Dispose();message = null;}
  if(client != null){client.Dispose();client = null;}
}
catch (Exception ex)
{
	Response.Write(ex.ToString());
}

로컬 SMTP 서비스로 발송하는 것과 다른 점은 SMTP 클라이언트 객체를 생성하는 부분만 다릅니다.

  SmtpClient client = new SmtpClient("smtp.cafe24.com", 587)
  {
    Credentials = new NetworkCredential("emailaddress@domain.com", "이메일패스워드"),
    EnableSsl = true
  };

SMTP 클라이언트 객체의 네트워크 크리덴셜(접속 정보)을 추가로 설정해야 인증 후 SMTP 서비스로 메일을 발송할 수 있습니다.