In this article, we will look into as how can we generate a pdf file from a HTML source and make that pdf as an attachment and send email. Also we have used the Exception Filters of C# 6.0 for retry count if the Email can not be sent for the first time because of any reason.
Introduction
iText is a open source project for java that helps to generate the pdf file. And iTextSharp is the .NET port that uses the iText library for generating the pdf files dynamically from any kind of source which can be a database, model, xml,json etc. We have a very good article in DotNetFunda written by Mr.Sheo Narayan, the founder of DotNetFunda.com where he talked about Dynamically generate .pdf in ASP.NET using iTextSharp library. In this article, we will look into as how can we generate a pdf file from a HTML source and make that pdf as an attachment and send email. Also we have used the Exception Filters of C# 6.0 for retry count if the Email cannot be send for the first time because of any reason.
Environment Setup
Open Visual Studio 2015 and fire up a Console Application. Then by using the Nuget Package Manager GUI, let us install iTextSharp

We can equally do the same from the Nuget Package Manager Console by issuing the below command
Install-Package iTextSharp
At the time of writing this article, the version is iTextSharp.5.5.7
Using the code
We have the below main functions
static void Main(string[] args)
{
//Step 1: Prepare the email content
var emailContent = GetEmailContent();
//Step 2: Generate the PDF and hold in memory
var attachment = GetAttachment(emailContent);
//Step 3: Send Email
var sendEmail = SendEmail(attachment, emailContent);
}
In the first step, we are prepare the email content.For this to happen, we have a dedicated class call EmailTemplate
using System.Text;
namespace ConsoleApplication7
{
public class EmailTemplate
{
StringBuilder sbEmailMsg;
public string GetEmailContent()
{
sbEmailMsg = new StringBuilder();
ComposeEmail();
return sbEmailMsg.ToString();
}
#region Private methods
private void ComposeEmail()
{
EmailHeader();
EmailBody();
EmailFooter();
}
private void EmailHeader()
{
sbEmailMsg.Append("<html><head><body><h2><center><u>RNA Pdf Content - made by RNA Team</u></center></h2>");
}
private void EmailBody()
{
sbEmailMsg.Append("<p>This is a test mail from <font color='blue' size='4'>RNA Team</font></p><p>This is a sample generated pdf by using <b><a href='http://sourceforge.net/projects/itextsharp/'>iTextSharp</a></b>.Click on the iTextSharp text to know more about it.</p><p>Have a nice day</p><p><span style='color:blue;'><strong><em>Regards RNA Team</em></strong></span>");
}
private void EmailFooter()
{
sbEmailMsg.Append("</body></html>");
}
#endregion
}
}
The ComposeEmail() function is the one that is composing the email content as is return as a string
Once the email has been composed, the next task is to form the attachment.
private static Attachment GetAttachment(string emailContent)
{
var file = ConvertHtmlToPDF(emailContent);
file.Seek(0, SeekOrigin.Begin);
Attachment attachment = new Attachment(file, "RNATeam.pdf", "application/pdf");
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = System.DateTime.Now;
disposition.ModificationDate = System.DateTime.Now;
disposition.DispositionType = DispositionTypeNames.Attachment;
return attachment;
}
In the first line itself we can figure out that, we have a function that converts the Html content to PDF by using iTextSharp.The ConvertHtmlToPDF function is as under.
private static MemoryStream ConvertHtmlToPDF(string emailContent)
{
//Create a MemoryStream which will hold the data
var ms = new MemoryStream();
//Create an iTextSharp Document
using (var doc = new Document())
{
//Create a pdf writer that will hold the instance of PDF abstraction which is doc and the memory stream
var writer = PdfWriter.GetInstance(doc, ms);
//Open the document for writing
doc.Open();
//Create a new HTMLWorker bound to our document
using (var htmlWorker = new iTextSharp.text.html.simpleparser.HTMLWorker(doc))
{
//HTMLWorker needs a TextReader (in this case a StringReader) to read string
using (var sr = new StringReader(emailContent))
{
//Parse the HTML
htmlWorker.Parse(sr);
}
}
writer.CloseStream = false;
//close the document
doc.Close();
//return the stream
return ms;
}
}
Since the above program is heavily documented, needless to explain anything further on that.Once the Attachment is ready, the final step is to send that in Email.So the purpose of the function SendEmail(attachment, emailContent)
private static string SendEmail(Attachment attachment,string emailContent)
{
return new EmailProvider().Send("senderName@test.com"
, "senderAddress@test.com"
, "recipientName@test.com"
, "recipientAddress@test.com"
, "replyToAddress@test.com"
, "Sub: Pdf attachment sent from RNA Team by using iTextSharp"
, emailContent
, EmailProvider.Format.Html
, attachment, null, null);
}
The SendEmail method inside the Send method looks as under
do
{
try
{
smtp.Send(message);
done = true;
response = "Email send successfully";
}
//observe the usage of Exception filters of C# 6.0
catch (SmtpException smtpEx) when (retryCount++ <= 5)
{
response = smtpEx.Message;
}
//observe the usage of Exception filters of C# 6.0
catch (Exception ex) when (retryCount++ <= 5)
{
response = ex.Message;
}
} while (!done);
return response;
A careful observation reveals that, we are using the new C# 6.0's Exception filters
After the email is sent successfully, we will receive the below

Once we open the pdf file it looks as under

References
Overview of iTextSharp
Conclusion
In this article we have learnt how to send Pdf file as attachement in Email using iTextSharp.Thanks for reading. Zip file attached
N.B.~The solution was built using VS2015.