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

本文关键字:电子邮件 设置 | 更新日期: 2023-09-27 18:06:32

我添加了一个这样的附件:

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

但我想把它附加为一个不同的名称,实际的文件名很长,令人困惑。我希望它附加为"file.txt",有没有一种简单的方法可以做到这一点,而不必复制文件?

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

怎么样:

System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(attachmentPath);
attachment.Name = "file.txt";  // set name here
msg.Attachments.Add(attachment);

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

var fs = new FileStream("attachmentPath", FileMode.Open);
var attachment = new System.Net.Mail.Attachment(fs, "MyAttachmentName.txt", "text/text");
var attachment = new Attachment(path){
    Name = "File Name"
};
msg.Attachments.Add(attachment);

所以我所做的基本上是创建附件并在初始化中添加名称。