Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a csv and attach to email and send in c#

This is how i am currently creating a table and sending it in an email. What i would like to do is instead of creating a table and sending it as text in the email i would like to create a csv file and attach it to this email and then send this. could someone please help show me how this can be done? thanks

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\"}"; }
    }
like image 292
Beginner Avatar asked Jan 19 '12 16:01

Beginner


1 Answers

Once you have generated the CSV file, you need to write it to a stream. You can then add the 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\"}";
  }
}

Reference for System.Net.Mail.Attachment class

like image 128
James Shuttler Avatar answered Oct 16 '22 18:10

James Shuttler