首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Visual C# 發送電子郵件實戰:完整 WinForms 郵件用戶端程式碼(三)

     編輯:關於C語言

程式運行介面

郵件發送程式介面
圖:Send.cs 程式運行介面,含寄件者、收件者、主旨、附件、內文等完整欄位

完整原始碼:Form1


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Web;
using System.Web.Mail;

public class Form1 : Form {
  // 控件宣告
  Label lblFrom, lblTo, lblSubject, lblCC, lblBCC, lblAttach;
  TextBox txtFrom, txtTo, txtSubject, txtCC, txtBCC, txtAttach, txtBody;
  Button btnSend, btnExit, btnBrowse;
  OpenFileDialog dlgOpen;
  Container components = null;

  public Form1() { InitializeComponent(); }

  protected override void Dispose(bool disposing) {
    if (disposing && components != null) components.Dispose();
    base.Dispose(disposing);
  }

  void InitializeComponent() {
    // ... 所有控件初始化、位置、大小、TabIndex、事件綁定 ...
    // 關鍵綁定:
    btnBrowse.Click += new EventHandler(btnBrowse_Click);
    btnSend.Click += new EventHandler(btnSend_Click);
    btnExit.Click += new EventHandler(btnExit_Click);
  }

  [STAThread]
  static void Main() { Application.Run(new Form1()); }

  // 發送按鈕核心邏輯
  void btnSend_Click(object sender, EventArgs e) {
    try {
      MailMessage msg = new MailMessage();
      msg.From = txtFrom.Text;
      msg.To = txtTo.Text;
      msg.Cc = txtCC.Text;
      msg.Bcc = txtBCC.Text;
      msg.Subject = txtSubject.Text;
      msg.Body = txtBody.Text;
      if (txtAttach.Text.Length > 0)
        msg.Attachments.Add(new MailAttachment(txtAttach.Text, MailEncoding.Base64));
      SmtpMail.Send(msg);
      MessageBox.Show("郵件已發送至 → " + txtTo.Text);
    } catch (Exception ex) {
      MessageBox.Show(ex.Message);
    }
  }

  void btnExit_Click(object sender, EventArgs e) { Application.Exit(); }

  void btnBrowse_Click(object sender, EventArgs e) {
    if (dlgOpen.ShowDialog() == DialogResult.OK)
      txtAttach.Text = dlgOpen.FileName;
  }
}

關鍵技術點

  1. System.Web.Mail 命名空間: .NET Framework 內建郵件類別,無需第三方庫。
  2. MailMessage: 封裝郵件所有屬性,支援多收件者(逗號分隔)、抄送、密件副本、Base64 附件編碼。
  3. SmtpMail.Send: 靜態方法透過本機/遠端 SMTP 伺服器發送,需機器設定有效 SMTP 服務(IIS SMTP 或外部伺服器)。
  4. OpenFileDialog: 附件選取對話方塊,回傳完整路徑供 MailAttachment 使用。
  5. 例外處理: 統一 try/catch 捕獲 SMTP 連線失敗、認證錯誤、附件不存在等錯誤,友善提示使用者。

總結

利用 .NET Framework 豐富的 System.Web.Mail 類別庫,僅需少量代碼即可構建功能完備的郵件發送用戶端。掌握框架類庫精髓,是 C# 高效開發的關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved