I am trying to send an email when my application crashes with an attached file describing the issue (Error details is gathered from a database). I've tried creating the file without attaching it to an email and it works fine (with data gathered from a database). Here is an example very close to what I have :
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();
I also tried :
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);
}
}
The file is attached to the email, has a size, but is empty. What am I doing wrong?
Thanks in advance.