System.Net.Mail.Attachment 的中文标题bug

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值