无法通过邮件创建和发送动态 CSV 文件作为附件

Unable to create and send dynamic CSV file as attachment over mail

我正在尝试创建动态 csv 文件并将其作为邮件附件发送,但它不起作用。我可以发送带附件的邮件,但文件是空的。下面是我的代码:

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)
      {
      }

谁能帮我解决这个问题?

由于您刚刚完成对流的写入,Position 属性 将设置为流的末尾。此外,可能仍有一些数据缓冲在尚未刷新到流的写入器中。因此,当从流中创建附件时,它看起来是空的。要解决此问题,请执行以下操作:

// Done writing here //

writer.Flush();
stream.Position = 0;

// Create attachment here //