0

Scenario: From FrontEnd user will give subject,body,attach 1 or more file (can be any format(pdf,excel,jpeg))

Issue: I wrote below code and getting email perfectly, but am not able to open attached file in received mail ,

                bool fileFound = false;
                byte[] bytes = new byte[] { };
                using (MailMessage mail = new MailMessage())
                {
                    var from = new MailAddress("****.com", "notification Order");
                    mail.Subject = Subject;
                    string header = Body;
                    string footer = 
                    mail.Body = header + footer;

                    if (Request.Form.Files.Count > 0)
                    {
                        var files = Request.Form.Files;
                        foreach (var data in files)
                        {
                            fileFound = true;
                            if (data.Length > 0)
                            {
                                //var fileName = ContentDispositionHeaderValue.Parse(data.ContentDisposition).FileName.Trim('"');
                                using (var reader = new StreamReader(data.OpenReadStream()))
                                {
                                    string contentAsString = reader.ReadToEnd();
                                    bytes = new byte[contentAsString.Length * sizeof(char)];
                                    System.Buffer.BlockCopy(contentAsString.ToCharArray(), 0, bytes, 0, bytes.Length);

                                    MemoryStream stream2 = new MemoryStream(bytes);
                                    string filename = Path.GetFileName(data.FileName);
                                    mail.Attachments.Add(new Attachment(stream2, filename));

                                }
                            }
                        }
                    }


                    mail.IsBodyHtml = true;
                    mail.From = from;
                    

Please help me out (MVC 6)

Baba Ranjith
  • 196
  • 14
  • 1
    Rather than read the files in as a string, convert to bytes & create a MemoryStream, which is likely to cause errors (you cannot treat the contents of a pdf file as a string) - could you add the attachment directly using its full pathname _mail.Attachments.Add(new Attachment(pathname));_ Or look at this : https://stackoverflow.com/questions/10353913/streamreader-vs-binaryreader – PaulF Feb 20 '23 at 11:48
  • hai , ya but my files are getting from UI (frontEnd) am not saving it anywhere . to pick path in mail.Attachments.Add(new Attachment(pathname));. – Baba Ranjith Feb 20 '23 at 11:55
  • See the edit re. BinaryReader rather than StreamReader. – PaulF Feb 20 '23 at 11:57

0 Answers0