Lah*_*hib 5 .net c# attachment smtpclient
我在工作中创建了一个应用程序,它从一些数据库数据生成exel文件.生成文件后,它们会自动发送给相关客户.我的问题是,当我运行已发布的应用程序时,它工作正常.但是一些用户在运行应用程序时,文件生成完美,因为它们保存在硬盘上,我可以看到它们.但是当它们附加到MailMessage对象时,它们就会被破坏.这是损坏文件的图像.这些文件应该是Excel文件.

这是我发送包含附件的邮件的代码:
public void SendMailedFilesDK()
{
string[] sentFiles = Directory.GetFiles(sentFilesDK);
if (sentFiles.Count() > 0)
{
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("ares"))
{
using (System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage())
{
msg.From = new MailAddress("system@mail.dk");
msg.To.Add(new MailAddress("operation@mail.dk"));
msg.To.Add(new MailAddress("bl@mail.dk"));
msg.CC.Add("lmy@mail.dk");
msg.CC.Add("ltr@mail.dk");
msg.Subject = "IBM PUDO";
msg.Body = sentFiles.Count() + " attached file(s) has been sent to the customer(s) in question ";
msg.IsBodyHtml = true;
foreach (string file in sentFiles)
{
Attachment attachment = new Attachment(file);
msg.Attachments.Add(attachment);
}
client.Send(msg);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当其他人运行应用程序时,为什么文件会被破坏?我们都在使用office 2010.
您应该确保将附件的内容类型设置为适当的值。
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet对于 xlsx 文件,或者
application/vnd.ms-excel对于 xls 文件。
例如,您的循环应该如下所示。
ContentType xlsxContent = new ContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
foreach (string file in sentFiles)
{
Attachment attachment = new Attachment(file, xlsxContent);
msg.Attachments.Add(attachment);
}
Run Code Online (Sandbox Code Playgroud)