所需方法:
我想在将文件作为附件发送时保留相同的文件名,而不是让 .NET 重命名它(无论出于何种原因它添加到文件的路径中)。 我不想传递另一个参数来设置文件名。
示例:
- Project (folder)
- Content (folder)
- Files (folder)
- PDF (folder)
- Triumeq (folder)
- sample.pdf (file)
电子邮件附件中的文件名始终重命名为:
DOMAINcontentfilespdftriumeqsample.pdf
域 = 在图像中标记
我尝试过的事情:
// add attachment if applicable
if (!string.IsNullOrEmpty(attachmentFilePath))
{
var fs = new FileStream(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, attachmentFilePath), FileMode.Open, FileAccess.Read);
msg.Attachments.Add(new Attachment(fs, fs.Name, MimeTypesHelper.GetContentType(Path.GetExtension(fs.Name))));
// MimeTypeHelper.GetContentType just returns the MimeType of the file listed in the file stream
}
或
if (!string.IsNullOrEmpty(attachmentFilePath))
{
msg.Attachments.Add(new Attachment(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, attachmentFilePath)));
}
每种方式总是重命名文件,并且不保留原始文件名
最佳答案
您使用的附件构造函数需要 Mime ContentType 的 Name
属性值作为第二个参数。当您传递带有斜杠的字符串时,它们只是作为不允许的字符被删除。
文件附件名称中不能包含某些路径,仅允许使用纯文件名。因此,您应该从路径中提取文件名,例如:
msg.Attachments.Add(new Attachment(fs, Path.GetFileName(fs.Name), MimeTypesHelper.GetContentType(Path.GetExtension(fs.Name))));
这将使附件名称成为“sample.pdf”。
关于c# - .NET SMTP 邮件 - 附件文件名被重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41077876/