I searched everywhere, but without finding any solution. The problem is: I'm trying to send e-mails with attachments from an ASP.NET MVC3 application. The problem is: the attachment is (or should be) a pdf file created with iTextSharp. I already have a method in a Controller that returns an ActionResult, and this method produces a pdf response. The problem is: how can I get teh file from this ActionResult?
-
this is not specific to MVC. wrap the pdf generation code in a method and use that to get the attachment. There are a lot of example to send emails in C#Shyju– Shyju2012-08-09 20:54:54 +00:00Commented Aug 9, 2012 at 20:54
-
1Maybe this is the better solution.Pierpaolo Paris– Pierpaolo Paris2012-08-09 21:18:39 +00:00Commented Aug 9, 2012 at 21:18
Add a comment
|
2 Answers
Move your code which generates the PDF fike stream to a method which you can Re Use in many places and use that when creating the attachment
public Byte[] GetGeneratedPDF(string someParameter)
{
//Do your magic to create the PDF and return the byte array
}
Now you can call this method to create the Attachement
MailMessage msg = new MailMessage();
MemoryStream stream = new MemoryStream(GetGeneratedPDF("hi"));
Attachment att1= new Attachment(stream, "stack123.pdf");
msg.Attachments.Add(att1);
Comments
Just take the same logic that you use inside your "PDF generation action method" and add the Stream (or whatever iTextSharp returns) as an attatchment to your mail:
message.Attachments.Add(new Attachment(stream, "name", "mimeType"));
2 Comments
Pierpaolo Paris
I am trying this solution, but "extracting" a stream from an ActionResult object seems to be not possible.
philipproplesch
No, not from the ActionResult but from the PDF generator. Have a look at Shyju's answer, this should make it clear.