c# - iTextSharp - 在电子邮件附件中发送内存中的 pdf

标签 c# email pdf itextsharp

我在这里问了几个问题,但仍有问题。如果您能告诉我我在代码中做错了什么,我将不胜感激。我从 ASP.Net 页面运行上面的代码并得到“无法访问已关闭的流”。

var doc = new Document();

MemoryStream memoryStream = new MemoryStream();

PdfWriter.GetInstance(doc, memoryStream);
doc.Open();
doc.Add(new Paragraph("First Paragraph"));
doc.Add(new Paragraph("Second Paragraph"));

doc.Close(); //if I remove this line the email attachment is sent but with 0 bytes 

MailMessage mm = new MailMessage("username@gmail.com", "username@gmail.com")
{
    Subject = "subject",
    IsBodyHtml = true,
    Body = "body"
};

mm.Attachments.Add(new Attachment(memoryStream, "test.pdf"));
SmtpClient smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    Credentials = new NetworkCredential("username@gmail.com", "my_password")
};

smtp.Send(mm); //the "Cannot Access a Closed Stream" error is thrown here

谢谢!!!

编辑:

只是为了帮助寻找这个问题的答案的人,发送附加到电子邮件的 pdf 文件而无需实际创建文件的代码如下(感谢 Ichiban 和 Brianng):

var doc = new Document();
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);

doc.Open();
doc.Add(new Paragraph("First Paragraph"));
doc.Add(new Paragraph("Second Paragraph"));

writer.CloseStream = false;
doc.Close();
memoryStream.Position = 0;

MailMessage mm = new MailMessage("username@gmail.com", "username@gmail.com")
{
    Subject = "subject",
    IsBodyHtml = true,
    Body = "body"
};

mm.Attachments.Add(new Attachment(memoryStream, "filename.pdf"));
SmtpClient smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    Credentials = new NetworkCredential("username@gmail.com", "password")

};

smtp.Send(mm);

最佳答案

你试过吗:

PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);

// Build pdf code...

writer.CloseStream = false;
doc.Close();

// Build email

memoryStream.Position = 0;
mm.Attachments.Add(new Attachment(memoryStream, "test.pdf"));

如果我没记错的话,这解决了之前项目中的类似问题。

参见 http://forums.asp.net/t/1093198.aspx

关于c# - iTextSharp - 在电子邮件附件中发送内存中的 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1196059/

相关文章:

linux - 如何使用 perl 更改邮件探测中的 ip

java - Java中的扫描仪可以读取pdf文件吗?使用流读取

html - 如何在移动版 Safari 中设置 pdf 宽度

vb.net - 如何使用 VB.NET 将 XLS 中的单个工作表转换为 PDF

c# - IndexOutOfRangeExpection 发生在 Dictionary.Add 方法上

php - 如何向客户发送 WooCommerce 新订单电子邮件?

c# - .Net 应用程序安装 2012 与数据库

objective-c - 将电子邮件从 mail.app 放入 NSWindow 对象

c# - 在 .Net 解决方案中将委托(delegate)放在哪里

c# - 随机不是那么随机,在 Windows Phone 7 上有随机类