响应邮件附件

时间:2012-07-03 15:01:47

标签: c# asp.net email httpresponse

using (MemoryStream stream = new MemoryStream())
            {
                compositeLink.PrintingSystem.ExportToPdf(stream);
                Response.Clear();
                Response.Buffer = false;
                Response.AppendHeader("Content-Type", "application/pdf");
                Response.AppendHeader("Content-Transfer-Encoding", "binary");
                Response.AppendHeader("Content-Disposition", "attachment; filename=test.pdf");
                Response.BinaryWrite(stream.GetBuffer());
                Response.End();


            }

我的工作正常。下一步是将此pdf文件作为附件发送到邮件

using (MemoryStream stream = new MemoryStream())
            {
                compositeLink.PrintingSystem.ExportToPdf(stream);
                Response.Clear();
                Response.Buffer = false;
                Response.AppendHeader("Content-Type", "application/pdf");
                Response.AppendHeader("Content-Transfer-Encoding", "binary");
                Response.AppendHeader("Content-Disposition", "attachment; filename=test.pdf");
                Response.BinaryWrite(stream.GetBuffer());




                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.To.Add("someone@example.net");
                message.Subject = "Subject";
                message.From = new System.Net.Mail.MailAddress("someoneelse@example.net");
                message.Body = "Body";
                message.Attachments.Add(Response.BinaryWrite(stream.GetBuffer()));
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("192.168.100.100");
                smtp.Send(message);

                Response.End();

        }

我对这一行有疑问:

message.Attachments.Add(Response.BinaryWrite(stream.GetBuffer()));

任何帮助如何使这个工作?感谢

3 个答案:

答案 0 :(得分:3)

Response.BinaryWrite将获取流的内容并将其写入响应。你不希望这样。

相反,您必须创建一个新的Attachment对象并将其添加到message.Attachments。

试试这个:

var ct = new ContentType();
ct.MediaType = MediaTypeNames.Application.Pdf;
ct.Name = "test.pdf";
message.Attachments.Add(new Attachment(stream, ct));

您可以找到更多示例代码here

答案 1 :(得分:3)

尝试这样的事情;

message.Attachments.Add(New Attachment(stream, "test.pdf", "application/pdf"))

答案 2 :(得分:0)

Response.BinaryWrite方法返回void,这意味着您没有将任何内容传递给Add方法。

您应该考虑做的是直接使用您的流来创建Attachment实例,并将其添加到邮件的集合中。这看起来像是:

message.Attachments.Add(new Attachment(stream, "file.pdf"));

可以在MSDN here上找到发送附件邮件的完整示例。希望有所帮助。