How to create csv and attach to email and send in C #

This is how I create the table now and send it by email. What I would like to do is instead of creating a table and sending it as text in an email, I would like to create a csv file and attach it to this email, and then send it. can someone please help show me how to do this? thank

using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv)))
    {
        try
        {
            string to = "";
            string from = "";
            string subject = "Order";
            string body = sb.ToString();
            SmtpClient SMTPServer = new SmtpClient("127.0.0.1");
            MailMessage mailObj = new MailMessage(from, to, subject, body); 
            mailObj.Attachments.Add(new Attachment(stream, new ContentType("text/csv")));
            mailObj.IsBodyHtml = true;
            SMTPServer.Send(mailObj);
        }
        catch (Exception ex)
        { return "{\"Error\":\"Not Sent\"}"; }
    }
+5
source share
2 answers

Once you have created the CSV file, you need to write it to the stream. Then you can add an attachment with the following code:

//Stream containing your CSV (convert it into bytes, using the encoding of your choice)
using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv)))
{
  //Add a new attachment to the E-mail message, using the correct MIME type
  Attachment attachment = new Attachment(stream, new ContentType("text/csv"));
  attachment.Name = "test.csv";
  mailObj.Attachments.Add(attachment);

  //Send your message
  try
  {
    using(SmtpClient client = new SmtpClient([host]){Credentials = [credentials]})
    {
      client.Send(mailObj);
    }
  }
  catch
  {
    return "{\"Error\":\"Not Sent\"}";
  }
}

Link for System.Net.Mail.Attachment class

+14
source

( CSV), MailMessage.

, :
( ) #?

0

All Articles