Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File are corrupted when Attaching them to MailMessage C#

I have created an application at work that generates exel files from some database data. After generating the files they are sent automatically to the customers in question. My problem is that it works fine when i run the published application. But some users when they run the application the files are generated perfectly as they are saved on the HDD and i can see them. But when they are attached to the MailMessage object they get corrupted. This is an image of the corrupted files. These files should be Excel files.

enter image description here

This is my code for sending a 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("[email protected]");
                        msg.To.Add(new MailAddress("[email protected]"));
                        msg.To.Add(new MailAddress("[email protected]"));
                        msg.CC.Add("[email protected]");
                        msg.CC.Add("[email protected]");
                        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 are the files getting corrupted when others run the application? We are all using office 2010.

like image 810
Lahib Avatar asked Nov 04 '22 01:11

Lahib


1 Answers

You should make sure to set the content type of the attachement to the appropriate value.

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for xlsx files, or

application/vnd.ms-excel for xls files.

For example, your loop should look something like this.

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);
}
like image 91
Jason Watkins Avatar answered Nov 12 '22 12:11

Jason Watkins