这些天使用 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。