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

标签 c# .net email csv .net-2.0

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

相关文章:

c# - XNA C# 如何让我的模型闪烁?

c# - 通过静态对象的静态属性访问 asp.net session 变量是否安全?

.net - 一对一的可选关系,两端可选且两个 FK

email - 如何禁用后缀地址验证

c# - 对数字中的数字求和的最快方法

c# - 使用反射创建 lambda 表达式,如 x => new { .. }

c# - 如何动态或在运行时设置 PropertyGrid 的 DefaultValueAttribute?

.NET 垃圾收集器基础知识

php - 如何在 Windows XP 上安装适用于 php 5.3.5 的 openssl?

html - 如何将 MS Outlook 笑脸 (Wingdings) 转换为可在浏览器中显示的内容?