如何创建csv并附加到电子邮件并发送到c#

前端之家收集整理的这篇文章主要介绍了如何创建csv并附加到电子邮件并发送到c#前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这就是我目前正在创建一个表并通过电子邮件发送它的方式.我想做的是不是创建一个表并将其作为文本发送到电子邮件中我想创建一个csv文件并将其附加到此电子邮件然后发送.请有人帮忙告诉我这是怎么做到的?谢谢
  1. using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv)))
  2. {
  3. try
  4. {
  5. string to = "";
  6. string from = "";
  7. string subject = "Order";
  8. string body = sb.ToString();
  9. SmtpClient SMTPServer = new SmtpClient("127.0.0.1");
  10. MailMessage mailObj = new MailMessage(from,to,subject,body);
  11. mailObj.Attachments.Add(new Attachment(stream,new ContentType("text/csv")));
  12. mailObj.IsBodyHtml = true;
  13. SMTPServer.Send(mailObj);
  14. }
  15. catch (Exception ex)
  16. { return "{\"Error\":\"Not Sent\"}"; }
  17. }

解决方法

生成CSV文件后,需要将其写入流.然后,您可以使用以下代码添加附件:
  1. //Stream containing your CSV (convert it into bytes,using the encoding of your choice)
  2. using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv)))
  3. {
  4. //Add a new attachment to the E-mail message,using the correct MIME type
  5. Attachment attachment = new Attachment(stream,new ContentType("text/csv"));
  6. attachment.Name = "test.csv";
  7. mailObj.Attachments.Add(attachment);
  8.  
  9. //Send your message
  10. try
  11. {
  12. using(SmtpClient client = new SmtpClient([host]){Credentials = [credentials]})
  13. {
  14. client.Send(mailObj);
  15. }
  16. }
  17. catch
  18. {
  19. return "{\"Error\":\"Not Sent\"}";
  20. }
  21. }

参考System.Net.Mail.Attachment

猜你在找的C#相关文章