如何创建csv并附加到电子邮件并发送到c#
发布时间:2020-12-15 18:00:19 所属栏目:百科 来源:网络整理
导读:这就是我目前正在创建一个表并通过电子邮件发送它的方式.我想做的是不是创建一个表并将其作为文本发送到电子邮件中我想创建一个csv文件并将其附加到此电子邮件然后发送.请有人帮忙告诉我这是怎么做到的?谢谢 using (MemoryStream stream = new MemoryStream
|
这就是我目前正在创建一个表并通过电子邮件发送它的方式.我想做的是不是创建一个表并将其作为文本发送到电子邮件中我想创建一个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"}"; }
}
解决方法
生成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"}";
}
}
参考System.Net.Mail.Attachment类 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
