Saya telah mengajukan beberapa pertanyaan di sini tetapi masih mengalami masalah. Saya akan menghargai jika Anda dapat memberi tahu saya kesalahan apa yang saya lakukan dalam kode saya. Saya menjalankan kode di atas dari halaman ASP.Net dan mendapatkan "Tidak Dapat Mengakses Arus Tertutup".
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
Terima kasih!!!
EDIT:
Sekadar membantu seseorang mencari jawaban atas pertanyaan ini, kode untuk mengirim file pdf yang dilampirkan ke email tanpa harus membuat file secara fisik ada di bawah ini (terima kasih kepada Ichiban dan 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);
position=0
. selamatkan aku!