I am trying to create and send dynamic csv file as attachment over mail, but it is not working. I am able to send mail with attachement, but file is going as empty. Below is my code:
var notProcessedRecords = FileFTPData.Where(x => x.LastName.StartsWith("9999")).ToList();
string loggedInUserName = "Administrator";
try
{
MemoryStream stream = new MemoryStream();
TextWriter writer = new StreamWriter(stream, Encoding.Default);
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("{0}, {1}, {2}, {3}, {4}, {5} ", "FIRSTNAME", "LASTNAME", "USERID", "COMPANYNAME", "EMAIL", "PHONE"));
foreach (var item in notProcessedRecords)
{
sb.AppendLine();
sb.AppendFormat(string.Format("{0}, {1}, {2}, {3}, {4}, {5} ", item.FirstName, item.LastName, item.UserId, item.CompanyName, item.Email, item.Phone));
}
writer.WriteLine(sb);
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("******@gmail.com");
mail.To.Add("*******@yahoo.com");
mail.Subject = "FTP file processing status";
mail.Body = "<div>Hello " + loggedInUserName + ", </br></br> Following item are restricted from processing, due to some errors. Please check Process description for the same. </br></br> From, </br>Streben Support </div>";
mail.IsBodyHtml = true;
Attachment attachment = new Attachment(stream, new ContentType("text/csv"));
attachment.Name = "test.csv";
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("******@gmail.com", "******");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch(Exception ex)
{
}
Can anybody help me in correcting the issue?
As you have just finished writing to the stream the Position
property will be set to the end of the stream. Additionally, there may still be some data buffered in the writer that hasn't been flushed to the stream. Because of this, when the attachment is created from the stream it will appear to be empty. To fix this do:
// Done writing here //
writer.Flush();
stream.Position = 0;
// Create attachment here //