Search code examples
c#.netemail-attachments

attachment files shows blank


this is my code, i am trying to send text file as attachment without storing it onto the disk....................................

            MailMessage mailMsg = new MailMessage();
            SmtpClient smtpClient = new SmtpClient();

            mailMsg.To.Add("receiver@email.com");
            mailMsg.Subject = "Application Exception";

            MemoryStream MS = new MemoryStream();
            StreamWriter Writer = new StreamWriter(MS);
            Writer.Write(DateTime.Now.ToString() + "hello");
            Writer.Flush();
            Writer.Dispose();

            // Create attachment
            ContentType ct = new ContentType(MediaTypeNames.Text.Plain);
            Attachment attach =new Attachment(MS, ct);
            attach.ContentDisposition.FileName = "Exception Log.txt";

            // Add the attachment
            mailMsg.Attachments.Add(attach);

            // Send Mail via SmtpClient
            mailMsg.Body = "An Exception Has Occured In Your Application- \n";
            mailMsg.IsBodyHtml = true;
            mailMsg.From = new MailAddress("sender@email.com");
            smtpClient.Credentials = new NetworkCredential("sender@email.com", "password");
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.Send(mailMsg);

Solution

  • Since you've written in the MemoryStream, the position is at the end of the stream. Set it back to the beginning by adding:

    MS.Seek(0, SeekOrigin.Begin);
    

    right after you've finished writing to the stream and flushing the writer. So (part of) your code would look like this:

    ...
    MemoryStream MS = new MemoryStream();
    StreamWriter Writer = new StreamWriter(MS);
    Writer.Write(DateTime.Now.ToString() + "hello");
    Writer.Flush();
    MS.Seek(0, SeekOrigin.Begin);
    ...
    

    EDIT:
    You should avoid calling Dispose on your writer, since it also closes the underlying stream.