这就是我目前正在创建一个表并通过电子邮件发送它的方式.我想做的是不是创建一个表并将其作为文本发送到电子邮件中我想创建一个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\"}";
}
}