Search code examples
c#pdfemail-attachmentsasp.net-webpageswebmail

Attaching a dynamically made pdf to a email c# .net Webpages


I am trying to attach a pdf that is made in with NReco.PdfGenerator to a email the system sends out.

I have:-

Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");
     var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
    var pdfBytes = htmlToPdf.GeneratePdfFromFile("http://{siteName}/templates/PasswordResetEmail2.cshtml", null);
    Response.BinaryWrite(pdfBytes);

And this works to out put a pdf to the save pop up window.

But i need to get this onto my system email,

WebMail.Send(
     to: email,
     subject: "Please see attached invoice",
     body: BodyTemplate,
     isBodyHtml: true,
     filesToAttach: invoice.pdf);

Hope you can help.


Solution

  • Hi Olivier below was correct on this i just needed a few other things to make it work.

    As i'm new to asp.net webpages i needed to declare a line at the top of the file first to make SMTPClient work.

    @using System.Net.Mail;
    

    Then put the smtp info in the web config.

    <system.net>
        <mailSettings>
          <smtp>
            <network host="host_name" port="25" userName="user name" password="password" defaultCredentials="false" />
          </smtp>
        </mailSettings>
    

    Then create the email.

    SmtpClient smtpClient = new SmtpClient(WebMail.SmtpServer);
                MailMessage email1 = new MailMessage();
                email1.IsBodyHtml = true;
                email1.From = new MailAddress("[email protected]");
                email1.To.Add(new MailAddress(sendemail));
                //email1.CC.Add(new MailAddress("[email protected]"));
                email1.Body = BodyTemplate;
                email1.Subject = "Please reset your password";
    
                var stream = new System.IO.MemoryStream(pdfBytes);
                email1.Attachments.Add(new Attachment(stream, "invoice.pdf"));
                smtpClient.Send(email1);