본문 바로가기
📁 [4] 개발자 정보 & 코드 노트/C#

C# Windows Forms 강의 91편: SMTP를 활용한 이메일 전송 애플리케이션 제작

by wawManager 2025. 5. 5.

 

1. 강의 개요

이번 강의에서는 **SMTP(Simple Mail Transfer Protocol)**를 활용해
이메일을 전송할 수 있는 애플리케이션을 제작합니다.
사용자는 수신자 이메일 주소, 제목, 내용을 입력하고,
첨부 파일을 추가하여 이메일을 전송할 수 있습니다.
.NET에서 제공하는 System.Net.Mail 네임스페이스를 사용해
간단하면서도 강력한 이메일 전송 기능을 구현합니다.


2. 학습 목표

  • System.Net.Mail 네임스페이스를 사용한 이메일 전송
  • 첨부 파일 추가 및 전송 기능 구현
  • 사용자 친화적인 이메일 입력 UI 제작
  • SMTP 서버와의 연결 및 전송 오류 처리

3. 기능 요구사항

필수 기능

1️⃣ 기본 이메일 전송:

  • 수신자, 제목, 내용을 입력받아 이메일 전송

2️⃣ 첨부 파일 추가:

  • 파일 첨부 및 전송

3️⃣ UI 구성 및 동작:

  • 직관적인 이메일 전송 UI 구성

4. 실습: 이메일 전송 애플리케이션 제작

1️⃣ 폼 구성

  • 폼(Form) 이름: Form1
  • 컨트롤 배치:

컨트롤 타입 이름 위치 크기

TextBox txtRecipient 폼 상단 왼쪽 (400 x 30)
TextBox txtSubject 폼 상단 왼쪽 아래 (400 x 30)
TextBox txtBody 폼 중간 전체 (400 x 150)
Button btnAttach 폼 하단 왼쪽 (100 x 30)
Label lblAttachment 폼 하단 중앙 (300 x 30)
Button btnSend 폼 하단 오른쪽 (100 x 30)

📌 폼 디자인 예시:

--------------------------------------------------
| [Recipient TextBox]                            |
| [Subject TextBox]                              |
| [Body TextBox - 이메일 내용 입력]              |
--------------------------------------------------
| [Attach 버튼] [첨부 파일 이름 표시 Label] [Send 버튼]|
--------------------------------------------------

2️⃣ 코드 작성

(1) 기본 이메일 전송 기능

using System;
using System.Net;
using System.Net.Mail;
using System.Windows.Forms;

namespace WindowsFormsApp_Email
{
    public partial class Form1 : Form
    {
        private string _attachmentPath; // 첨부 파일 경로

        public Form1()
        {
            InitializeComponent();
        }

        // 이메일 전송
        private void btnSend_Click(object sender, EventArgs e)
        {
            string recipient = txtRecipient.Text.Trim();
            string subject = txtSubject.Text.Trim();
            string body = txtBody.Text.Trim();

            if (string.IsNullOrEmpty(recipient) || string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(body))
            {
                MessageBox.Show("모든 필드를 입력하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                SendEmail(recipient, subject, body);
                MessageBox.Show("이메일이 성공적으로 전송되었습니다.", "완료", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"이메일 전송 실패: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SendEmail(string recipient, string subject, string body)
        {
            // SMTP 클라이언트 설정
            using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
            {
                smtp.Credentials = new NetworkCredential("your_email@gmail.com", "your_app_password");
                smtp.EnableSsl = true;

                // 메일 메시지 생성
                MailMessage mail = new MailMessage
                {
                    From = new MailAddress("your_email@gmail.com"),
                    Subject = subject,
                    Body = body,
                    IsBodyHtml = false // HTML 형식 여부
                };
                mail.To.Add(recipient);

                // 첨부 파일 추가
                if (!string.IsNullOrEmpty(_attachmentPath))
                {
                    Attachment attachment = new Attachment(_attachmentPath);
                    mail.Attachments.Add(attachment);
                }

                // 이메일 전송
                smtp.Send(mail);
            }
        }
    }
}

(2) 첨부 파일 추가 기능

        // 첨부 파일 추가
        private void btnAttach_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "모든 파일 (*.*)|*.*";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    _attachmentPath = openFileDialog.FileName;
                    lblAttachment.Text = $"첨부 파일: {System.IO.Path.GetFileName(_attachmentPath)}";
                }
            }
        }

(3) Designer 코드

        private void InitializeComponent()
        {
            this.txtRecipient = new TextBox();
            this.txtSubject = new TextBox();
            this.txtBody = new TextBox();
            this.btnAttach = new Button();
            this.lblAttachment = new Label();
            this.btnSend = new Button();

            // Recipient TextBox 설정
            this.txtRecipient.Location = new System.Drawing.Point(10, 10);
            this.txtRecipient.Size = new System.Drawing.Size(400, 30);
            this.txtRecipient.PlaceholderText = "Recipient Email";

            // Subject TextBox 설정
            this.txtSubject.Location = new System.Drawing.Point(10, 50);
            this.txtSubject.Size = new System.Drawing.Size(400, 30);
            this.txtSubject.PlaceholderText = "Subject";

            // Body TextBox 설정
            this.txtBody.Location = new System.Drawing.Point(10, 90);
            this.txtBody.Size = new System.Drawing.Size(400, 150);
            this.txtBody.Multiline = true;
            this.txtBody.ScrollBars = ScrollBars.Vertical;
            this.txtBody.PlaceholderText = "Email Body";

            // Attach Button 설정
            this.btnAttach.Location = new System.Drawing.Point(10, 250);
            this.btnAttach.Size = new System.Drawing.Size(100, 30);
            this.btnAttach.Text = "Attach";
            this.btnAttach.Click += new EventHandler(this.btnAttach_Click);

            // Attachment Label 설정
            this.lblAttachment.Location = new System.Drawing.Point(120, 250);
            this.lblAttachment.Size = new System.Drawing.Size(300, 30);

            // Send Button 설정
            this.btnSend.Location = new System.Drawing.Point(320, 250);
            this.btnSend.Size = new System.Drawing.Size(100, 30);
            this.btnSend.Text = "Send";
            this.btnSend.Click += new EventHandler(this.btnSend_Click);

            // Form 설정
            this.ClientSize = new System.Drawing.Size(450, 300);
            this.Controls.Add(this.txtRecipient);
            this.Controls.Add(this.txtSubject);
            this.Controls.Add(this.txtBody);
            this.Controls.Add(this.btnAttach);
            this.Controls.Add(this.lblAttachment);
            this.Controls.Add(this.btnSend);
            this.Text = "SMTP 이메일 전송 애플리케이션";
        }

3️⃣ 실행 결과

1️⃣ 이메일 전송

  • 수신자 이메일, 제목, 내용을 입력 → "Send" 버튼 클릭 → 이메일 전송

2️⃣ 첨부 파일 추가

  • "Attach" 버튼 클릭 → OpenFileDialog로 파일 선택 → 첨부 파일 표시

5. 주요 개념 요약

  • SmtpClient: SMTP 서버와 통신하여 이메일 전송
  • MailMessage: 이메일 메시지 작성 및 설정
  • Attachment: 이메일 첨부 파일 추가
  • OpenFileDialog: 파일 선택 대화 상자

 

📌 #CSharp #WindowsForms #SMTP #Email #첨부파일 #OpenFileDialog