7

i have code that generates a pdf file and i want to send it as an attachment to an email .

I have this code:

        FileContentResult fileContentResult = File(fileName, "application/pdf", "file.pdf");

and i have this code to email an attachment

        Attachment a = new Attachment();
        sender.SendMail("a@a.com", "a@a.com", "subject", "Body", a);

how do i convert a FileContentResult into a Attachment object?

leora
  • 188,729
  • 360
  • 878
  • 1,366
  • You probably want to use stuff the FileContents property of your FileContentResult instance into a memorystream and send. The memorystream bit is shown here http://stackoverflow.com/questions/1196059/itextsharp-sending-in-memory-pdf-in-an-email-attachment – Tahbaza Jul 20 '10 at 22:04

2 Answers2

11

Have you tried using this: Attachment Constructor (Stream, ContentType)?

Something like

MemoryStream ms = new MemoryStream(fileContentResult.FileContents); 
// Create an in-memory System.IO.Stream

ContentType ct = new ContentType(fileContentResult.ContentType);

Attachment a = new Attachment(ms, ct);
MrBoJangles
  • 12,127
  • 17
  • 61
  • 79
  • @Moron - this code doesn't compile. i have renamed that variable above. this line is not recognized: ContentType ct = stream.ContentType; – leora Jul 20 '10 at 22:09
  • @ooo: You need `using System.IO`, do you have that? Also edited code as stream.ContentType was apparently string. –  Jul 20 '10 at 22:10
  • @Moron - this line is not recognized: ContentType ct = stream.ContentType; – leora Jul 20 '10 at 22:11
1

I am just 7 years late, but here is your answer:

Attachment a = new Attachment(fileName, "application/pdf");
sender.SendMail("a@a.com", "a@a.com", "subject", "Body", a);
JP Hellemons
  • 5,977
  • 11
  • 63
  • 128