結合網路程式設計、Windows Forms 系統匣應用、COM 元件互通,打造實用的郵件到達通知工具。
Timer 觸發定期檢查using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;
private NetworkStream netStream;
private void EmailCheck() {
TcpClient tcpClient = new TcpClient();
try {
tcpClient.Connect(serverAddress.Text, int.Parse(serverPort.Text));
} catch {
MessageBox.Show($"無法連線至 {serverAddress.Text}:{serverPort.Text}");
return;
}
netStream = tcpClient.GetStream();
if (netStream == null) throw new Exception("網路串流為空");
string response = ReadFromNetStream(ref netStream);
CheckForError(response);
// POP3 認證流程
WriteToNetStream(ref netStream, "USER " + username.Text);
response = ReadFromNetStream(ref netStream);
CheckForError(response);
WriteToNetStream(ref netStream, "PASS " + password.Text);
response = ReadFromNetStream(ref netStream);
CheckForError(response);
// 取得郵件統計
Stat();
netStream.Close();
tcpClient.Close();
}
private void WriteToNetStream(ref NetworkStream ns, string cmd) {
byte[] data = Encoding.ASCII.GetBytes(cmd + "\r\n");
ns.Write(data, 0, data.Length);
}
private string ReadFromNetStream(ref NetworkStream ns) {
StreamReader sr = new StreamReader(ns);
StringBuilder sb = new StringBuilder();
string line;
while ((line = sr.ReadLine()) != null) {
sb.AppendLine(line);
if (!sr.Peek().Equals(-1)) continue;
break;
}
return sb.ToString();
}
private void CheckForError(string response) {
if (response.StartsWith("-ERR"))
throw new Exception("伺服器錯誤: " + response);
}
private void Stat() {
WriteToNetStream(ref netStream, "STAT");
string response = ReadFromNetStream(ref netStream);
CheckForError(response);
// 回應格式: +OK 郵件數 總大小
string[] parts = response.Split(' ');
int count = int.Parse(parts[1]);
int totalSize = int.Parse(parts[2]);
// 呼叫精靈表單通知
Form2 agent = new Form2(count);
agent.Show();
}
// Form1 建構函式
public Form1() {
InitializeComponent();
this.Opacity = 0; // 隱藏主視窗
this.ShowInTaskbar = false; // 不在工作列顯示
timer1.Interval = int.Parse(timeSpan.Text); // 設定檢查間隔
timer1.Enabled = true;
}
// Timer Tick 事件
private void timer1_Tick(object sender, EventArgs e) {
Thread t = new Thread(EmailCheck);
t.Start();
}
// 系統匣右鍵選單事件
private void menuConfig_Click(object sender, EventArgs e) {
this.Opacity = 100; // 顯示設定視窗
this.ShowInTaskbar = true;
}
private void menuExit_Click(object sender, EventArgs e) {
Application.Exit();
}
Microsoft Agent Control (ActiveX)| 技術 | 類別/元件 | 用途 |
|---|---|---|
| TCP 連線 | TcpClient, NetworkStream | POP3 通訊基礎 |
| 非同步檢查 | Thread + Timer | 避免封鎖 UI |
| 系統匣 | NotifyIcon, ContextMenu | 背景常駐、右鍵選單 |
| 精靈 | Agent Control (COM) | 語音/動畫通知 |
| 文字編碼 | Encoding.ASCII.GetBytes | 網路傳輸位元組轉換 |
System.Net.Mail.Pop3Client (第三方) 或 MailKit 成熟函式庫async/await 取代手動 Thread 管理ProtectedData)