I am trying to create a .txt file dynamically and also after creating it with some content I need to send the same in attachment of email. Email sending with attachment working for me but the attached file is empty.
I am trying below code to do the same -
using (var ms = new System.IO.MemoryStream())
{
using (var writer = new System.IO.StreamWriter(ms))
{
StringBuilder sb = new StringBuilder();
sb.Append("Filte start here");
sb.AppendFormat("<test>{0}</test>", test);
sb.Append("File end here");
writer.Write(sb.ToString());
writer.Flush();
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = "temp.txt";
mail.Attachments.Add(attach);
try
{
SendEmailUtility.SendMail(mail);
}
catch (SmtpException e)
{
Console.WriteLine(e.ToString());
}
}
}
It is not the duplicate of Attach a file from MemoryStream to a MailMessage in C# post because I am also doing the same thing what is suggested there but in my case sending empty attachment. So definitively there is something which I am missing in my code base.
Please let me know what I am doing wrong here.
Any help would be appreciated!