在C#中设置电子邮件附件名称

我添加这样的附件:

System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentPath);   
msg.Attachments.Add(attachment);   

但我想将其附加为一个不同的名称,实际文件名非常长且令人困惑,我希望将其附加为“ file.txt”,是否有一种简单的方法无需复制该文件 文件?

Tom Gullen asked 2020-08-10T22:55:46Z
2个解决方案
70 votes

怎么样:

System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(attachmentPath);
attachment.Name = "file.txt";  // set name here
msg.Attachments.Add(attachment);
Kev answered 2020-08-10T22:55:51Z
6 votes

您需要从流中加载附件,然后可以为其指定名称和媒体类型。

var fs = new FileStream("attachmentPath", FileMode.Open);
var attachment = new System.Net.Mail.Attachment(fs, "MyAttachmentName.txt", "text/text");
John Oxley answered 2020-08-10T22:56:11Z
translate from https://stackoverflow.com:/questions/7149148/set-email-attachment-name-in-c-sharp