Unicode字符在邮件附件名称中消失

时间:2014-07-22 07:19:42

标签: c# email unicode smtp

我开发了一个应用程序,需要通过电子邮件发送压缩文件(在附件中)。一切都很好,除了一件事:附件名称中的西里尔字母(或其他unicode)字符消失了。它们在消息名称和消息正文中工作正常,但不在附件中。

我使用以下代码进行附件:

var attachment = new Attachment(file, MediaTypeNames.Application.Zip);

ContentDisposition disposition = attachment.ContentDisposition;

disposition.CreationDate = File.GetCreationTime(file);
disposition.ModificationDate = File.GetLastWriteTime(file);
disposition.ReadDate = File.GetLastAccessTime(file);
disposition.FileName = Path.GetFileName(file);            
disposition.Size = new FileInfo(file).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;            
message.Attachments.Add(attachment);
smtpClient.Send(message);

使用SmtpClient Class发送电子邮件。我在SO上尝试了一些解决方法,比如

att.Name = "история-болезни.doc";  // non-english filename    
att.Name = System.Web.HttpUtility.UrlEncode(att.Name, System.Text.Encoding.UTF8);

但什么都没有......我的日志说电子邮件带有正确的附件名称进入服务器,我也试图手动发送这样的电子邮件(不是以编程方式),它也运行良好。

那么,我该如何解决这个问题呢?我找到了.Net框架的一些补丁,但它并不好,因为我必须将我的应用程序发布到许多不同的客户端,并且我不想在应用程序正常工作之前在他们的计算机上安装补丁程序。

UPD。 Letter Sample (In Outlook)

1 个答案:

答案 0 :(得分:1)

我的猜测是System.Net.Mail的附件文件编码器被破坏了,这意味着在继续使用它时可能无法解决这个问题。

但是,您可以使用MailKit来正确编码附件文件名。它允许您从System.Net.Mail.MailMessage转换为MimeKit.MimeMessage,这样可以很容易地移植它。

编辑:

要在MimeKit和MailKit中创建相同的消息,代码看起来像这样:

var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey@friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice@wonderland.com"));
message.Subject = "How you doin?";

var builder = new BodyBuilder ();

// Set the plain-text version of the message text
builder.TextBody = @"Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.

Will you be my +1?

-- Joey
";

// Add an attachment
builder.Attachments.Add (file);

var attachment = builder.Attachments[0];

// setting the attachment.FileName will set the Content-Disposition's filename
// parameter as well as the Content-Type's name parameter.
attachment.FileName = "история-болезни.doc";

// FWIW, very few, if any, mail clients actually care about these fields...
// they are optional and can be ignored.
//var disposition = attachment.ContentDisposition;
//disposition.CreationDate = File.GetCreationTime (file);
//disposition.ModificationDate = File.GetLastWriteTime (file);
//disposition.ReadDate = File.GetLastAccessTime (file);
//disposition.Size = new FileInfo (file).Length;

// Now we just need to set the message body and we're done
message.Body = builder.ToMessageBody ();

// Now send via MailKit's SmtpClient
smtpClient.Send (message);