MailMessage附件的文件名有口音口音、文件名、附件、MailMessage

2023-09-04 09:14:57 作者:沵是莪訫上的刀い

我试图用附加的Excel文件名发送HTML电子邮件。这一切运作良好,直到我neded发送邮件的附件名称中包含重音字母:-(每一个解决方法我试过悲惨地失败了。

I'm trying to send HTML e-mails with attached Excel filenames. It all worked well until I neded to send messages whose attachment name contains accented letters :-( Every workaround I've tried failed miserably.

原来的code:

  var attachment = new Attachment(
       new MemoryStream(excelFileContents),
       "simplefilename.xls");

这一次正常工作。 但是,如果我取代simplefilename.xls由échec.xls,附件被garbaged(名称和内容)。

This one works fine. However if I replace "simplefilename.xls" by "échec.xls", the attachment is garbaged (name and contents).

我尝试了这些,都无济于事:

I tried these, to no avail:

  var attachment = new Attachment(
       new MemoryStream(excelFileContents),
       new System.Net.Mime.ContentType("application/vnd.ms-excel"));
  attachment.Name = "échec.xls";

最后一个更糟糕的是: SmtpClient.Send()抛出一个异常,抱怨电子的文件名:

The last one is even worse: SmtpClient.Send() throws an exception, complaining about the é in the filename:

  var attachment = new Attachment(
       new MemoryStream(excelFileContents),
       new System.Net.Mime.ContentType("application/vnd.ms-excel"));
  attachment.ContentDisposition.FileName = "échec.xls";

我一直在敲打这一个太长了我的头。任何灯光热烈欢迎!

I've been banging my head on this one for way too long. Any lights warmly welcomed!

推荐答案

跨越奏效的答案,我终于来了。

I finally came across an answer that worked.

http://social.msdn.microsoft.com/Forums/en-US/dotnetframeworkde/thread/b6c764f7-4697-4394-b45f-128a24306d55

含量在德国以外的职位由Marcel罗马。我把他的code到我的应用程序。我能送出去的PDF与口音和我们看到的附件,而不是垃圾。

The content is in German except for the post by Marcel Roma. I put in his code into my application. I was able to send out pdf with accents and we were to see the attachment instead of garbage.

所以在这里,它是:

public class AttachmentHelper
{
    public static System.Net.Mail.Attachment CreateAttachment(string attachmentFile, string displayName, TransferEncoding transferEncoding)
    {
        System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(attachmentFile);
        attachment.TransferEncoding = transferEncoding;

        string tranferEncodingMarker = String.Empty;
        string encodingMarker = String.Empty;
        int maxChunkLength = 0;

        switch (transferEncoding)
        {
            case TransferEncoding.Base64:
                tranferEncodingMarker = "B";
                encodingMarker = "UTF-8";
                maxChunkLength = 30;
                break;
            case TransferEncoding.QuotedPrintable:
                tranferEncodingMarker = "Q";
                encodingMarker = "ISO-8859-1";
                maxChunkLength = 76;
                break;
            default:
                throw (new ArgumentException(String.Format("The specified TransferEncoding is not supported: {0}", transferEncoding, "transferEncoding")));
        }

        attachment.NameEncoding = Encoding.GetEncoding(encodingMarker);

        string encodingtoken = String.Format("=?{0}?{1}?", encodingMarker, tranferEncodingMarker);
        string softbreak = "?=";
        string encodedAttachmentName = encodingtoken;

        if (attachment.TransferEncoding == TransferEncoding.QuotedPrintable)
            encodedAttachmentName = HttpUtility.UrlEncode(displayName, Encoding.Default).Replace("+", " ").Replace("%", "=");
        else
            encodedAttachmentName = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(displayName));

        encodedAttachmentName = SplitEncodedAttachmentName(encodingtoken, softbreak, maxChunkLength, encodedAttachmentName);
        attachment.Name = encodedAttachmentName;

        return attachment;
    }

    private static string SplitEncodedAttachmentName(string encodingtoken, string softbreak, int maxChunkLength, string encoded)
    {
        int splitLength = maxChunkLength - encodingtoken.Length - (softbreak.Length * 2);
        var parts = SplitByLength(encoded, splitLength);

        string encodedAttachmentName = encodingtoken;

        foreach (var part in parts)
            encodedAttachmentName += part + softbreak + encodingtoken;

        encodedAttachmentName = encodedAttachmentName.Remove(encodedAttachmentName.Length - encodingtoken.Length, encodingtoken.Length);
        return encodedAttachmentName;
    }

    private static IEnumerable<string> SplitByLength(string stringToSplit, int length)
    {
        while (stringToSplit.Length > length)
        {
            yield return stringToSplit.Substring(0, length);
            stringToSplit = stringToSplit.Substring(length);
        }

        if (stringToSplit.Length > 0) yield return stringToSplit;
    }
}

使用它以下列方式:

static void Main(string[] args)
{
    string smtpServer = String.Empty;
    string userName = String.Empty;
    string password = String.Empty;
    string attachmentFilePath = String.Empty;
    string displayName = String.Empty;

    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpServer);
    client.Credentials = new System.Net.NetworkCredential(userName, password);

    var msg = new System.Net.Mail.MailMessage(fromAddress, toAddress, "Subject", "Body");
    System.Net.Mail.Attachment attachment =
         AttachmentHelper.CreateAttachment(attachmentFilePath, displayName, TransferEncoding.Base64);

    msg.Attachments.Add(attachment);
    client.Send(msg);
}