如何创建csv并附加到电子邮件并以c#发送
本文关键字:电子邮件 发送 创建 csv 何创建 | 更新日期: 2023-09-27 18:20:53
这就是我当前创建表并通过电子邮件发送的方式。我想做的是创建一个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类的引用
您应该首先创建一个临时文件(CSV文件),然后将附件添加到MailMessage
中
要创建临时文件,可以查看以下链接:
如何在C#中创建一个临时文件(用于写入)
创建临时文件夹