来自内存流的电子邮件附件在C#中显示为空白

时间:2015-02-11 12:53:04

标签: c# .net email email-attachments memorystream

我可以通过邮件发送附件,但附件内容为空白,大小显示为0字节。

通过互联网进行一些搜索后发现我们需要将内存流位置重置为0才能从开始开始。

我也试过了,但它似乎无法正常工作。你能帮忙吗?

请在下面找到我的代码段:

注意:我可以保存工作簿,并且数据存在于保存的工作簿中。

        MemoryStream memoryStream = new MemoryStream();

        StreamWriter writer = new StreamWriter(memoryStream);
        writer.Write(xlWorkbook);
        writer.Flush();
        memoryStream.Position = 0;
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtpclient");
        mail.From = new MailAddress("from@gmail.com");
        mail.To.Add("To@gmail.com");
        mail.Subject = "Entry";
        mail.Body = "Hello, PFA ";
        System.Net.Mail.Attachment attachment;

        attachment = new System.Net.Mail.Attachment(memoryStream,"xls");
        attachment.ContentDisposition.FileName = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
        mail.Attachments.Add(attachment);
        SmtpServer.Port = 465;
        SmtpServer.UseDefaultCredentials = false;
        SmtpServer.Credentials = new System.Net.NetworkCredential("Username", "password");
        SmtpServer.EnableSsl = true;
        SmtpServer.Send(mail);
        writer.Dispose();

1 个答案:

答案 0 :(得分:4)

我认为附件使邮件系统混乱。 Microsoft的建议是将内容类型指定为octet。以下是初始化附件的替代品。重置代码看起来很好。

string filename = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
attachment = new System.Net.Mail.Attachment(memoryStream, filename, MediaTypeNames.Application.Octet);