gpt4 book ai didi

c# - 如何创建一个 csv 并附加到电子邮件并在 C# 中发送

转载 作者:太空狗 更新时间:2023-10-29 17:37:06 29 4
gpt4 key购买 nike

这就是我目前创建表格并通过电子邮件发送的方式。我想做的不是创建表格并将其作为电子邮件中的文本发送,而是创建一个 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

关于c# - 如何创建一个 csv 并附加到电子邮件并在 C# 中发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8929538/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com