C# - 无法将文件附加到电子邮件

C# - cannot attach file to an email

我有一个创建 Excel 文件并通过电子邮件发送的服务。

此服务在测试服务器上正常工作,但在生产服务器上我有一个错误 - 附件中有一个奇怪的文件,没有扩展名,名称像这样 =utf-8B0J3QtdC0YDQvtGB0YLQsNCy0LvQtdC9 并且里面的内容相同而不是 Excel 文件.

有我的发送方式。我想我的代码没有问题。

public static void SendEmail(string subject, string body, string recipients, Attachment attachment = null)
    {
        string mailServer = Settings.Default.MailServer;

        MailMessage message = new MailMessage(Settings.Default.MailSender, recipients);
        foreach (string address in Settings.Default.MailCopyTo.Split(',').Select(x => x.Trim()))
        {
            if (!string.IsNullOrEmpty(address))
                message.CC.Add(new MailAddress(address));
        }
        message.IsBodyHtml = true;
        message.Body = body;
        message.Subject = subject;

        if(attachment != null)
            message.Attachments.Add(attachment);


        SmtpClient client = new SmtpClient(mailServer);
        var AuthenticationDetails = new NetworkCredential(Settings.Default.MailLogin, Settings.Default.MailPassword);
        client.Credentials = AuthenticationDetails;
        client.Send(message);
    }

.NET Framework 中存在一个错误,附件的文件名超过 41 个 unicode 字符。

我也遇到了同样的问题并通过将文件名截断为 40 个字符来修复它。我做了什么:

  1. 获取文件扩展名
  2. 获取不带扩展名的文件名
  3. 将文件名缩短为 40 - extension.Length 个字符
  4. 添加扩展程序

我引用了an MSDN thread中的一个答案:

Yes we are aware of this problem and have already addressed it for future releases. [...]

In .NET 4.0 SmtpClient now implements the RFC line length limits (76 chars). This required extensive changes to the encoding process and we have uncovered a few issues like the one you describe.

In your case, yes, there is an issue with non-ascii attachment names that would be encoded to more than 41 utf-8 bytes (Encoding.UTF8.GetByteCount(fileName);). In this scenario the names are encoded twice and may have extra line breaks in them. The only known workaround is to limit the length of non-ascii file names.