公司因發送大量相同內容郵件被國際反垃圾組織列入黑名單,導致客戶收不到信。解決方案:改為定時任務將查詢結果打包成附件,由主控台程式定時寄送,降低單封郵件體積與頻率。
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Collections;
namespace SendEmail {
class Program {
static void Main(string[] args) {
Console.WriteLine(SendEmailWithAttachment());
Console.ReadKey();
}
public static string SendEmailWithAttachment() {
// === 郵件伺服器設定 (請替換為實際值) ===
string smtpServer = "***.***.***.***"; // SMTP IP/主機名
int smtpPort = 25; // 或 587 (TLS), 465 (SSL)
string from = "sender@company.com";
string to = "receiver@client.com";
string cc = "cc@company.com";
string subject = "每日報表 - " + DateTime.Now.ToString("yyyy-MM-dd");
string body = "您好,附件為今日業務報表,請查收。";
// === 建立郵件物件 ===
MailMessage mail = new MailMessage();
mail.From = new MailAddress(from);
mail.To.Add(to);
if (!string.IsNullOrEmpty(cc)) mail.CC.Add(cc);
mail.Subject = subject;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = body;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = false; // 純文字;HTML 郵件設 true 並調整 Body
// === 加入附件 ===
string attachmentPath = @"D:\Reports\DailyReport_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
if (System.IO.File.Exists(attachmentPath)) {
Attachment att = new Attachment(attachmentPath, MediaTypeNames.Application.Octet);
// 解決中文檔名亂碼 (RFC 2231)
att.ContentDisposition.FileName = System.Net.Mime.MimeUtility.Encode(att.Name);
mail.Attachments.Add(att);
}
// === SMTP 客戶端設定 ===
SmtpClient client = new SmtpClient(smtpServer, smtpPort) {
// 若需認證
// Credentials = new NetworkCredential("account", "password"),
// EnableSsl = true, // 587/465 埠通常需啟用
// DeliveryMethod = SmtpDeliveryMethod.Network,
// Timeout = 30000
};
try {
client.Send(mail);
return "郵件發送成功:" + DateTime.Now;
} catch (SmtpException ex) {
return "SMTP 錯誤:" + ex.StatusCode + " - " + ex.Message;
} catch (Exception ex) {
return "發送失敗:" + ex.Message;
} finally {
mail.Dispose();
client.Dispose();
}
}
}
}
| 屬性 | 用途 | 常見值 |
|---|---|---|
| EnableSsl | 啟用 SSL/TLS 加密 | true (Gmail/Outlook/企業郵箱多要求) |
| Port | 連接埠 | 25(無加密), 587(STARTTLS), 465(SSL) |
| Credentials | 驗證憑證 | new NetworkCredential("user", "pwd") |
| DeliveryMethod | 投遞方式 | Network (預設), SpecifiedPickupDirectory |
| Timeout | 逾時毫秒 | 30000 (30秒) |
// 錯誤:中文檔名在某些郵件客戶端顯示亂碼
Attachment att = new Attachment(path);
// 正確:使用 MimeUtility.Encode 進行 RFC 2231 編碼
att.ContentDisposition.FileName = MimeUtility.Encode(Path.GetFileName(path));
app.config / appsettings.jsonawait client.SendMailAsync(mail) 避免阻塞此主控台程式可直接編譯為 .exe,配合 Windows 排程器或 SQL Server Agent 定時執行,實現自動化報表寄送。