JMail (Dimac JMail) 是經典的 ASP/ASP.NET 郵件發送 COM 元件。雖然年久但許多舊系統仍在使用。
using JMail;
public bool SendMail(string senderName, string senderEmail,
string recipient, string subject, string body)
{
try
{
var msg = new MessageClass();
// 基本設定
msg.Charset = "utf-8"; // 關鍵:使用 UTF-8 支援中文
msg.From = senderEmail;
msg.FromName = senderName;
msg.Subject = subject;
msg.Body = body;
// 收件者
msg.AddRecipient(recipient, "", "");
// SMTP 驗證
msg.MailServerUserName = "your_account";
msg.MailServerPassWord = "your_password";
// 發送 (同步阻塞)
return msg.Send("smtp.example.com", false);
}
catch (Exception ex)
{
// 記錄日誌
return false;
}
}
收件端收到附件檔名變成:`=?GB2312?Q?=B1=E3=CA=D4=2Epdf?=` 或亂碼
| 方案 | 程式碼關鍵 | 適用性 | 備註 |
|---|---|---|---|
| 1. 設定 Charset 為 UTF-8 | `msg.Charset = "utf-8";` | 現代客戶端佳 | 最簡單,建議首試 |
| 2. 明確指定 ContentType | `msg.AddAttachment(file, true, "application/pdf");` | 部分改善 | 第三參數為 MIME 類型 |
| 3. 避免設定 msg.ContentType | 註解掉 `msg.ContentType = "text/html"` | 關鍵修正 | 讓 JMail 自動產生 multipart 結構 |
| 4. 檔名僅保留 ASCII | 重新命名為 Guid + 副檔名 | 100% 相容 | 犧牲使用者體驗 |
| 5. 使用 AddURLAttachment | `msg.AddURLAttachment(url, "filename.pdf")` | 網路檔案 | 第二參數可指定顯示檔名 |
public bool SendMailWithAttachment(string senderName, string senderEmail,
string recipient, string subject, string body, string attachmentPath)
{
try
{
var msg = new MessageClass();
// 1. 字元編碼:UTF-8 為現代標準
msg.Charset = "utf-8";
// 2. 基本資訊
msg.From = senderEmail;
msg.FromName = senderName;
msg.Subject = subject;
msg.Body = body;
msg.AddRecipient(recipient, "", "");
// 3. SMTP 設定
msg.MailServerUserName = ConfigurationManager.AppSettings["SmtpUser"];
msg.MailServerPassWord = ConfigurationManager.AppSettings["SmtpPass"];
// 4. 關鍵:不要手動設定 ContentType!
// msg.ContentType = "text/html"; ← 這行會破壞 multipart 結構導致附件異常
// 5. 加入附件:使用 IsInline=false (附件模式),明確指定 MIME 類型
if (!string.IsNullOrEmpty(attachmentPath) && File.Exists(attachmentPath))
{
string mimeType = GetMimeType(Path.GetExtension(attachmentPath));
// AddAttachment(檔案路徑, IsInline, ContentType)
// 回傳 Content-ID 可用於 HTML 內嵌圖片
string cid = msg.AddAttachment(attachmentPath, false, mimeType);
}
// 6. 發送
bool success = msg.Send(
ConfigurationManager.AppSettings["SmtpServer"],
false); // false=同步發送
return success;
}
catch (Exception ex)
{
// Log.Error(ex);
return false;
}
}
private string GetMimeType(string extension)
{
return extension.ToLower() switch
{
".pdf" => "application/pdf",
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".doc" => "application/msword",
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".xls" => "application/vnd.ms-excel",
".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".zip" => "application/zip",
_ => "application/octet-stream"
};
}
string cid = msg.AddAttachment(imagePath, true, "image/png"); // true = Inline
msg.Body = $@"
內嵌圖片測試
";
JMail 屬於 COM 互操作技術,在 .NET Core / Linux 容器 / 雲端環境**無法運作**。建議遷移至:
| 方案 | 特色 | NuGet 套件 |
|---|---|---|
| MailKit | 純 .NET、支援 IMAP/SMTP/POP3、跨平台、積極維護 | MailKit |
| MimeKit | MailKit 姊妹專案,專注 MIME 訊息建構、編碼處理完美 | MimeKit |
| FluentEmail | 流暢 API、支援 Razor 模板、多發送器 (MailKit, SendGrid, SMTP) | FluentEmail.Core + FluentEmail.MailKit |
| SendGrid / Mailgun / Amazon SES | 雲端郵件服務、高送達率、統計分析、API 驅動 | 各官方 SDK |
using MailKit.Net.Smtp;
using MimeKit;
public async Task SendAsync(string to, string subject, string body, string attachmentPath)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("寄件者", "sender@example.com"));
message.To.Add(new MailboxAddress("收件者", to));
message.Subject = subject;
var builder = new BodyBuilder();
builder.HtmlBody = body;
if (!string.IsNullOrEmpty(attachmentPath) && File.Exists(attachmentPath))
{
// 自動處理檔名編碼 (RFC 2231/5987)
builder.Attachments.Add(attachmentPath);
}
message.Body = builder.ToMessageBody();
using (var client = new SmtpClient())
{
await client.ConnectAsync("smtp.example.com", 587, MailKit.Security.SecureSocketOptions.StartTls);
await client.AuthenticateAsync("user", "pass");
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
}
JMail 附件中文檔名亂碼的核心解決之道:設定 `Charset = "utf-8"` + 不手動設定 `ContentType` + 明確指定附件 MIME 類型。若仍有相容性問題,改用 ASCII 檔名或遷移至 MailKit/MimeKit 等現代純 .NET 函式庫是長久之計。MailKit 完美支援 RFC 2231/5987 國際化檔名編碼,徹底解決跨客戶端亂碼問題。