2012-07-03 79 views
-2
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("[email protected]"); 
       message.Subject = "Subject"; 
       message.From = new System.Net.Mail.MailAddress("[email protected]"); 
       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())); 

任何幫助如何得到這個工作?謝謝

回答

2

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

0

Response.BinaryWrite方法返回void這意味着您沒有將任何內容傳遞給Add方法。

你應該考慮做的是直接使用你的流創建一個Attachment實例,並將其添加到消息的集合中。這看起來是這樣的:

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

帶有附件的郵件發送完整的例子可以在MSDN here找到。希望有所幫助。

2

嘗試類似這樣;

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