gpt4 book ai didi

附加到 MailMessage 对象时的 C# 空文件

转载 作者:行者123 更新时间:2023-11-30 16:57:12 26 4
gpt4 key购买 nike

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

MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("Address1@test.com");
mailMessage.From = new MailAddress("Address2@test.com");
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("Address1@test.com");
mailMessage.From = new MailAddress("Address2@test.com");
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("Address1@test.com");
mailMessage.From = new MailAddress("Address2@test.com");
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/

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