将动态制作的 pdf 附加到电子邮件 c# .net 网页

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

我正在尝试将使用 NReco.PdfGenerator 制作的 pdf 附加到系统发送的电子邮件中。

我有:-

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);

这样可以将 pdf 保存到弹出窗口 window。

但我需要将其添加到我的系统电子邮件中,

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

希望能帮到你。

WebMail.Send() 似乎只能从硬盘发送文件。

您可以使用 System.Net.Mail.SmtpClient 发送 MailMessage。 MailMessage 有一种从 Stream 添加附件的方法,因此是使用 MemoryStream 的 byte[]。

SmtpClient smtpClient = new SmtpClient(WebMail.SmtpServer);
MailMessage email = new MailMessage(...);
var stream = new System.IO.MemoryStream(pdfBytes);
email .Attachments.Add(new Attachment(stream, "invoice.pdf"));
smtpClient.Send(email);

嗨,下面的 Olivier 在这方面是正确的,我只需要一些其他的东西来让它工作。

由于我是 asp.net 网页的新手,我需要先在文件顶部声明一行以使 SMTPClient 工作。

@using System.Net.Mail;

然后将 smtp 信息放入网络配置中。

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

然后创建电子邮件。

SmtpClient smtpClient = new SmtpClient(WebMail.SmtpServer);
            MailMessage email1 = new MailMessage();
            email1.IsBodyHtml = true;
            email1.From = new MailAddress("from@email.com");
            email1.To.Add(new MailAddress(sendemail));
            //email1.CC.Add(new MailAddress("carboncopy@foo.bar.com"));
            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);