我在这里问了几个问题,但仍然遇到问题。如果您能告诉我我的代码中做错了什么,我将不胜感激。我从 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("[email protected]", "[email protected]")
{
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("[email protected]", "my_password")
};
smtp.Send(mm); //the "Cannot Access a Closed Stream" error is thrown here
谢谢!!!
EDIT:
为了帮助某人寻找这个问题的答案,发送附在电子邮件中的 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("[email protected]", "[email protected]")
{
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("[email protected]", "password")
};
smtp.Send(mm);