Sending Mail With Dynamically Created PDF As Attachment In C#

Introduction

Emailing has become an essential part of communication in today's digital world. One of the frequent requirements is sending PDFs as email attachments. Sometimes, you may want to send a dynamically created PDF as an attachment in C#. This can be useful when you need to generate reports or invoices and email them to your clients or colleagues. 

This article will explore how to send an email with a dynamically created PDF as an attachment using C#.

Let's start with the code.

First, we created a new blank project in Asp.net Core Web App(MVC) with C#. Now we must install the NuGet package.

  1. NuGet\Install-Package iTextSharp -Version 5.5.13.3
  2. NuGet\Install-Package itextsharp.xmlworker -Version 5.5.13.3

Let's start the code.

string body = string.Empty;
_host.WebRootPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
string contentRootPath = _host.WebRootPath + "/test.html";
using(StreamReader reader = new StreamReader(contentRootPath)) {
    body = reader.ReadToEnd();
}
body = body.Replace("{title}", "Your First title");
body = body.Replace("{Header1}", "First Header");
body = body.Replace("{Header2}", "Second Header");
body = body.Replace("{currentdate}", DateTime.Now.ToString());

In the above code, create an HTML page used to create the pdf.

Now go to the wwwroot folder and create an HTML Page as test.html.

<!DOCTYPE html>
<html>
  <head>
    <title>{title}</title>
  </head>
  <body>
    <h1>{Header1}</h1>
    <h2>{Header2}</h2>
    <p>Pages (HTML)</p>
    <p>Style Sheets (CSS)</p>
    <p>Computer Code (JavaScript)</p>
    <p>Live Data (Files and Databases)</p>
    <p>{currentdate}</p>
  </body>
</html>

Now continue the code,

using(MailMessage mailMessage = new MailMessage()) {
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    byte[] ? bytesArray = null;
    using(var ms = new MemoryStream()) {
        var document = new Document();
        PdfWriter writer = PdfWriter.GetInstance(document, ms);
        document.Open();
        using(var strReader = new StringReader(body)) {
            //Set factories
            HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            //Set css
            ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
            string contentRootPath1 = _host.WebRootPath + "/css/site.css";
            cssResolver.AddCssFile(contentRootPath1, true);
            //Export
            IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
            var worker = new XMLWorker(pipeline, true);
            var xmlParse = new XMLParser(true, worker);
            xmlParse.Parse(strReader);
            xmlParse.Flush();
        }
        document.Close();
        bytesArray = ms.ToArray();
    }
    byte[] reader = {};
    mailMessage.IsBodyHtml = true;
    mailMessage.From = new MailAddress("[email protected]");
    mailMessage.Subject = "Test Payment Receipt";
    mailMessage.Body = "Please Find The Attachment";
    mailMessage.IsBodyHtml = true;
    mailMessage.Attachments.Add(new Attachment(new MemoryStream(bytesArray), "Test.pdf"));
    mailMessage.To.Add(new MailAddress("[email protected]"));
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.EnableSsl = true;
    System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
    NetworkCred.UserName = "[email protected]";
    NetworkCred.Password = "password";
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = NetworkCred;
    smtp.Port = 587;
    smtp.Send(mailMessage);
}

In the above code, the MemoryStream object ms holds the PDF content. And convert the HTML page to PDF. Now send this pdf file as an attachment using MailMessage.

We create a new MailMessage object mail and set the necessary properties, such as the sender, recipient, subject, and body. We then create an Attachment object using the MemoryStream object and add it to the mail message.

In the above example, I am using Gmail as a sender mail. If you also use Gmail as a sender mail, follow some steps.

In Gmail, you can't use your mail password. You must create the app password. Below are the steps to create the app password. 

  1. Log in to your Gmail.
  2. Now open https://myaccount.google.com. 
  3. Now go to security, and enable 2-Step Verification. 
  4. Now click the app password And Generate the App password,

that app password is used to send the mail. 

Finally, we create a new SmtpClient object client , set the necessary properties such as the SMTP server address, port number, and credentials, and enable SSL. We then use the Send() method of the SmtpClient object to send the email.

Conclusion

Sending an email with a dynamically created PDF as an attachment in C# is straightforward. You can use the MemoryStream object to hold the PDF content and create an Attachment object to attach to the mail message. With the SmtpClient object, you can send the email using the SMTP server. This can be useful when you need to generate reports or invoices on-the-fly and send them to your clients or colleagues. 


Similar Articles