這些天使用 SmtpClient 來發送郵件附件,碰到了一個 “在郵件標頭中找到無效的字符。” 的錯誤 。
見如下代碼:
private TransferEncoding _textTransferEncoding = TransferEncoding.SevenBit;
private TransferEncoding _binaryTransferEncoding = TransferEncoding.Base64;
private Encoding _characterEncoding = Encoding.GetEncoding("gb2312");
public Attachment GetAttachment()
{
string filePath = @"d:/中文文件.txt";
//string displayName = "=?gb2312?B?1tDOxM7EvP4udHh0?=";
string displayName = "中文文件.txt";
Attachment _attachment = new System.Net.Mail.Attachment(filePath);
_attachment.NameEncoding = _characterEncoding;
_attachment.ContentType.MediaType = "text/plain";
_attachment.ContentDisposition.Inline = false;
_attachment.ContentDisposition.FileName = "中文文件.txt";
//_attachment.ContentDisposition.FileName = "=?gb2312?B?1tDOxM7EvP4udHh0?=";
_attachment.ContentDisposition.CreationDate = System.IO.File.GetCreationTime(filePath);
_attachment.ContentDisposition.ModificationDate = System.IO.File.GetLastWriteTime(filePath);
_attachment.ContentDisposition.ReadDate = System.IO.File.GetLastAccessTime(filePath);
displayName = displayName.Replace(" ", string.Empty);
if (_attachment.ContentType.MediaType.ToLower().StartsWith("text/"))
{
_attachment.ContentType.CharSet = _characterEncoding.HeaderName;
_attachment.TransferEncoding = _textTransferEncoding;
}
else
{
_attachment.ContentType.CharSet = null;
_attachment.TransferEncoding = _binaryTransferEncoding;
}
return _attachment;
}
當文件名爲中文文件名時,這段代碼會出錯。但如果文件名是英文、數字、下劃線,則不會出錯。
通過反覆測試檢查後發現,當我把
_attachment.ContentDisposition.FileName = "中文文件.txt";
改成:
_attachment.ContentDisposition.FileName = "=?gb2312?B?1tDOxM7EvP4udHh0?=";
後,程序能夠運行通過。並且發送郵件附件沒有出現問題。
(=?gb2312?B?1tDOxM7EvP4udHh0?= 是“中文文件.txt”的Base64編碼後的形式)。
所以在設置 _attachment.ContentDisposition.FileName 的值時,需要進行編碼。
這個bug在老外寫的 MailMergeLib 裏也存在,老外並沒有修復這個bug,這可能是因爲老外沒用過中文的緣故,沒發現這個bug。