File corrupted when connected to MailMessage C #

I created an application at work that generates exel files from some database data. After the files are generated, they are automatically sent to the clients in question. My problem is that it works great when I run a published application. But some users, when starting the application, the files are generated perfectly, because they are saved on the hard drive, and I can see them. But when they are attached to the MailMessage object, they become damaged. This is an image of corrupted files. These files must be Excel files.

enter image description here

This is my code for sending mail with attached files:

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);
                    }
                }
            }
        }

Why do files get corrupted when others launch an application? We all use the 2010 office.

+5
3

, .

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);
}
+1

Attachment Excel PDF.

= (sFileName, MediaTypeNames.Application.Octet);

, , , , sentFilesDK.

+1

You might want to specify the mimetype type, which is part of one of the constructors of the Attachment class.

public Attachment (string fileName, ContentType contentType);

You can also read the file in memystream and pass it as part of the following constructor.

public Attachment (stream contentStream, line name, line mediaType);

0
source

All Articles