1

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?

2
  • 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# Commented Aug 9, 2012 at 20:54
  • 1
    Maybe this is the better solution. Commented Aug 9, 2012 at 21:18

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

I am trying this solution, but "extracting" a stream from an ActionResult object seems to be not possible.
No, not from the ActionResult but from the PDF generator. Have a look at Shyju's answer, this should make it clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.