MemoryStream ms = new MemoryStream();
PrintableComponentLink pcl = new PrintableComponentLink(new PrintingSystem());
pcl.Component = ASPxGridViewExporter1;
pcl.Margins.Left = pcl.Margins.Right = 50;
pcl.Landscape = true;
pcl.CreateDocument(false);
pcl.PrintingSystem.Document.AutoFitToPagesWidth = 1;
pcl.ExportToPdf(ms);
MailMessage mailMsg = new MailMessage();
mailMsg.To.Add("n@x.net");
MailAddress mailAddress = new MailAddress("info@x.net");
mailMsg.From = mailAddress;
mailMsg.Subject = "";
mailMsg.Body = "";
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, "x.pdf");
mailMsg.Attachments.Add(attach);
SmtpClient smtpClient = new SmtpClient("192.168.1.200", 25);
smtpClient.UseDefaultCredentials = false;
smtpClient.Send(mailMsg);
ms.Close();
我正在附件中获得153B文件。
我哪里错了?
答案 0 :(得分:0)
在附加流之前,最有可能ms.Position = 0
会处理它。
不太可能,但可能不需要关闭/处理流(但我不认为是同步发送邮件的情况)。
旁注:我有单独的MemoryStream
用于写作和阅读/发送。只需在原始流的缓冲区上创建只读流将使代码更清晰/更容易推理。下面的示例,也更好地使用其他构造函数,它采用缓冲区+长度而不是复制:
var streamToSend = new MemoryStream(ms.ToArray());
答案 1 :(得分:0)
我认为您需要将MemoryStream和ContentType传递给附件,而不是Memorystream和PDF名称。还要确保将ms设置为位置0。
尝试替换这些行
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, "x.pdf");
mailMsg.Attachments.Add(attach);
以下内容:
ms.Seek(0, SeekOrigin.Begin);
System.Net.Mime.ContentType ct= new System.Net.Mime.ContentType();
ct.MediaType = System.Net.Mime.MediaTypeNames.Application.Pdf;
ct.Name = "x.pdf";
Attachment attach = new Attachment(ms, contentType);
mailMsg.Attachments.Add(attach);
答案 2 :(得分:0)
不要将MemoryStream用作附件。 ExportToPdf接受从Stream派生的类型。而是将PDF导出为FileStream
。
pcl.ExportToPdf(fileStream);
然后附加FileStream并更正MIME类型:
var attach = new System.Net.Mail.Attachment(fileStream, "x.pdf", MediaTypeNames.Application.Pdf);
只需删除它将在此过程中创建的临时文件。无论出于何种原因,即使您设置MemoryStream.Position = 0;