c# - .NET SMTP 邮件 - 附件文件名被重命名

标签 c# .net email smtp

所需方法:

我想在将文件作为附件发送时保留相同的文件名,而不是让 .NET 重命名它(无论出于何种原因它添加到文件的路径中)。 我不想传递另一个参数来设置文件名。

示例:

- Project (folder)
 - Content (folder)
  - Files (folder)
   - PDF (folder)
    - Triumeq (folder)
     - sample.pdf (file)

电子邮件附件中的文件名始终重命名为:

DOMAINcontentfilespdftriumeqsample.pdf

域 = 在图像中标记

enter image description here

我尝试过的事情:

// 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/

相关文章:

C# - 如何使 AutoMapper 不区分大小写?

mysql - 是否可以将 EntityFramework 与 MemSQL 一起使用?

.net - Windows 托管的 WCF 服务可以使用 HTTPS 吗?

linux - 删除页脚的 procmail 配方

python - BCC 未使用 python smtplib 在 gmail 上隐藏

c# - 将项目移动到列表顶部时,WPF AlternationIndex 会回绕

c# - 监控线程创建

c# 字符串作为 html 属性

c# - Ndepend 和其他自动代码分析有什么关系?

email - AWS Lambda : How to extract attachment (xls) from raw email?