这就是我目前正在创建一个表并通过电子邮件发送它的方式。我想做的是不是创建一个表并将其作为文本发送到电子邮件中我想创建一个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\"}"; }
}
答案 0 :(得分:18)
生成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\"}";
}
}
的参考
答案 1 :(得分:0)
您应该先查看创建临时文件(CSV文件),然后将附件添加到MailMessage
。
要创建临时文件,您可以查看以下链接:
How to create a temporary file (for writing to) in C#?
Creating temporary folders