How to attach a file from MemoryStream to a Mail in C#

Here’s a simplified snippet for sending an in-memory string as an email attachment (a CSV file in this particular case).
If you are trying this with PDF, put special mention on stream.position = 0. As it will make the writer write the file from starting position always.
Whatever the source-type you care coming with convert that to memory-stream and the use the memory stream to create the attachment.
That’s it!!

using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))    // using UTF-8 encoding by default
using (var mailClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("me@example.com", "you@example.com", "Just testing", "See attachment..."))
{
    writer.WriteLine("Comma,Seperated,Values,...");
    writer.Flush();
    stream.Position = 0;     // read from the start of what was written

    message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));

    mailClient.Send(message);
}