萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

JMail 發送郵件與附件中文檔名亂碼完整解決方案

JMail 簡介與安裝

JMail (Dimac JMail) 是經典的 ASP/ASP.NET 郵件發送 COM 元件。雖然年久但許多舊系統仍在使用。

安裝步驟

  1. 下載 `JMail.dll` (通常含 `JMail.exe` 安裝程式)
  2. 複製到伺服器 `C:\Windows\System32\` (64位系統為 `SysWOW64`)
  3. 以管理員身分執行 CMD:`regsvr32 JMail.dll` 註冊 COM 元件
  4. 專案加入參考:`COM` → `JMail 4.x Type Library` → 產生 `Interop.JMail.dll`

基本發送郵件程式碼


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. JMail 內部使用 MIME 編碼 (RFC 2047) 編碼檔名
  2. 預設編碼為 `GB2312` (由 `msg.Charset` 決定)
  3. 部分郵件客戶端 (Outlook、Gmail、Apple Mail) 對 RFC 2047 解碼實作不一致
  4. 特別是 `Content-Disposition: inline` vs `attachment` 行為差異

解決方案總覽

方案程式碼關鍵適用性備註
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"
    };
}

HTML 郵件內嵌圖片 (CID 方式)


string cid = msg.AddAttachment(imagePath, true, "image/png"); // true = Inline
msg.Body = $@"
    
        

內嵌圖片測試

內嵌圖片 ";

遷移建議:現代郵件發送方案

JMail 屬於 COM 互操作技術,在 .NET Core / Linux 容器 / 雲端環境**無法運作**。建議遷移至:

方案特色NuGet 套件
MailKit純 .NET、支援 IMAP/SMTP/POP3、跨平台、積極維護MailKit
MimeKitMailKit 姊妹專案,專注 MIME 訊息建構、編碼處理完美MimeKit
FluentEmail流暢 API、支援 Razor 模板、多發送器 (MailKit, SendGrid, SMTP)FluentEmail.Core + FluentEmail.MailKit
SendGrid / Mailgun / Amazon SES雲端郵件服務、高送達率、統計分析、API 驅動各官方 SDK

MailKit 發送帶附件郵件範例 (現代標準)


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 國際化檔名編碼,徹底解決跨客戶端亂碼問題。

copyright © 萬盛學電腦網 all rights reserved