我正在尝试在我的应用程序崩溃时发送一封电子邮件,并附上描述问题的附件(错误详细信息是从数据库中收集的)。我试过在不将其附加到电子邮件的情况下创建文件,它工作正常(使用从数据库收集的数据)。这是一个非常接近我所拥有的示例:

MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("[email protected]");
mailMessage.From = new MailAddress("[email protected]");
mailMessage.Subject = "Subject";
mailMessage.Body = "Body";

FileStream fs = new FileStream("Test.txt", FileMode.Create, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Text");

Attachment attach = new Attachment(fs, "Test.txt", "Text/Plain");
mailMessage.Attachments.Add(attach);

SmtpClient smtp = new SmtpClient();

try
{
    smtp.Send(mailMessage);
}
catch(Exception ex)
{
     MessageBox.Show(ex.Message + Environment.NewLine + ex.InnerException);
}

sw.Close();

我也试过:
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("[email protected]");
mailMessage.From = new MailAddress("[email protected]");
mailMessage.Subject = "Subject";
mailMessage.Body = "Body";

using (FileStream fs = new FileStream("Test.txt", FileMode.Create, FileAccess.ReadWrite))
{
     StreamWriter sw = new StreamWriter(fs);
     sw.WriteLine("Text");


     Attachment attach = new Attachment(fs, "Test.txt", "Text/Plain");
     mailMessage.Attachments.Add(attach);

     SmtpClient smtp = new SmtpClient();

     try
     {
         smtp.Send(mailMessage);
     }
     catch (Exception ex)
     {
          MessageBox.Show(ex.Message + Environment.NewLine + ex.InnerException);
     }
}

该文件附加到电子邮件中,有大小,但为空。我究竟做错了什么?

提前致谢。

最佳答案

回答我自己的问题...找到答案 here

这是我使用的代码:

MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("[email protected]");
mailMessage.From = new MailAddress("[email protected]");
mailMessage.Subject = "Subject";
mailMessage.Body = "Body";

using (MemoryStream memoryStream = new MemoryStream())
{
     byte[] contentAsBytes = Encoding.UTF8.GetBytes("Test");
     memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length);

     memoryStream.Seek(0, SeekOrigin.Begin);
     ContentType contentType = new ContentType();
     contentType.MediaType = MediaTypeNames.Text.Plain;
     contentType.Name = "Test.txt";

      Attachment attach = new Attachment(memoryStream, contentType);
      mailMessage.Attachments.Add(attach);

      SmtpClient smtp = new SmtpClient();

      try
      {
          smtp.Send(mailMessage);
      }
      catch (Exception ex)
      {
          MessageBox.Show(ex.Message + Environment.NewLine + ex.InnerException);
      }
}

我使用了 MemoryStream 而不是 FileStream 。我还创建了一个内容类型对象,而不仅仅是在附件构造函数中指定 MediaType。

谢谢大家的帮助。

关于附加到 MailMessage 对象时的 C# 空文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26893172/

10-12 01:43