如何通过邮件消息C#发送MemoryStream文本Plain

时间:2013-11-07 15:53:00

标签: c# email attachment memorystream

我正在尝试将日志文件附加到我的邮件中,但我没有收到任何内容。这是我的榜样。我做错了什么?我可以看到我的文件log.txt被创建并放在路径中,但如果我尝试附加这部分,它就不会发送电子邮件。

private void AssignAttachment(MailMessage msg, DataTable dt, StreamReader streamreader)
{
    FileStream fs = (FileStream)streamreader.BaseStream;
    string file = "c:\\temp\\log.txt";
    using (StreamWriter sw = new StreamWriter(file, false, Encoding.GetEncoding("UTF-8")))
    {
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            //Testing. Col 0 = string results
            sw.WriteLine(dt.Rows[i][0]);
        }
    }

    MemoryStream ms = new MemoryStream();
    using (FileStream fileStream = File.OpenRead(file))
    {
        ms.SetLength(fileStream.Length);
        fileStream.Read(ms.GetBuffer(), 0, (int)fileStream.Length);
    }

    //MailMessage msg = new MailMessage();
    //msg is well-configured email. Sends emails if I don't attach anything
    msg.Attachments.Add(new Attachment(ms,file, System.Net.Mime.MediaTypeNames.Text.Plain);
}

1 个答案:

答案 0 :(得分:0)

由于Attachment接受Stream作为第一个参数,您应该能够指定FileStream而不是MemoryStream。这将消除对中间流的需求,并允许流式上传,而不是将整个文件加载到内存中。

在您编写文件后打开文件进行阅读时,只需将该流传递到Attachment构造函数即可。