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

前端之家收集整理的这篇文章主要介绍了如何创建csv并附加到电子邮件并发送到c#前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这就是我目前正在创建一个表并通过电子邮件发送它的方式.我想做的是不是创建一个表并将其作为文本发送到电子邮件中我想创建一个csv文件并将其附加到此电子邮件然后发送.请有人帮忙告诉我这是怎么做到的?谢谢 @H_502_2@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\"}"; } }

解决方法

生成CSV文件后,需要将其写入流.然后,您可以使用以下代码添加附件: @H_502_2@//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\"}"; } }

参考System.Net.Mail.Attachment

猜你在找的C#相关文章