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

Email Attachment from memory stream is coming as blank in C#

我可以在邮件中发送附件,但附件内容为空,大小显示为 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();

我认为附件混淆了邮件系统。 Microsoft 的建议是将内容类型指定为 octet。下面是初始化附件的替换。您的代码重置看起来不错。

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