如何创建一个csv并附加到电子邮件并在c#中发送
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8929538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a csv and attach to email and send in c#
提问by Beginner
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
这就是我目前创建表格并通过电子邮件发送的方式。我想做的是创建一个表格并将其作为电子邮件中的文本发送,而不是我想创建一个 csv 文件并将其附加到该电子邮件然后发送。有人可以帮我看看如何做到这一点吗?谢谢
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\"}"; }
}
采纳答案by James Shuttler
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:
生成 CSV 文件后,您需要将其写入流。然后,您可以使用以下代码添加附件:
//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.Attachmentclass
回答by Gabriel GM
You should look first to create a temporary file (CSV file), then you can add the attachment to your MailMessage.
To create the temp file, you can look at these links:
How to create a temporary file (for writing to) in C#?
Creating temporary folders
您应该首先创建一个临时文件(CSV 文件),然后您可以将附件添加到您的MailMessage.
要创建临时文件,您可以查看以下链接:
如何在 C# 中创建临时文件(用于写入)?
创建临时文件夹

