In this article I will explain with an example, how to send runtime generated file as Attachment in email in ASP.Net using C# and VB.Net.
This article will illustrate how to attach a runtime generated PDF file as attachment and send email in ASP.Net using C# and VB.Net.
 
 
Namespaces
You will need to add reference of iTextSharp DLL and then add the following namespaces.
C#
using System.IO;
using System.Text;
using System.Data;
using System.Net;
using System.Net.Mail;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
 

VB.Net
Imports System.IO
Imports System.Text
Imports System.Data
Imports System.Net
Imports System.Net.Mail
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
 
 
Send runtime generated file as Attachment in email using C# and VB.Net
Inside the Page Load event, first a DataTable is populated with some dummy records and then the DataTable is passed as parameter to the SendPDFEmail function.
Note: I have made use of ASP.Net PageLoad event but the same code can be used in Windows as well as Console applications.
 
Inside the SendPDFEmail function, an HTML string using the StringBuilder class is generated. This HTML string is basically a Receipt from a company containing the details of an Order.
The generated HTML is parsed and added to the PDF document. You will notice that I am generating the PDF writer instance using MemoryStream class, this is necessary to generate the PDF in memory.
Once the PDF processing is done, the MemoryStream is converted to Byte Array and then added as an attachment to the MailMessage class object and finally the email is sent.
For this example, I am making use of GMAIL server SMTP settings which can be replaced with the settings of any other mail server settings for sending emails.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] {
                                new DataColumn("OrderId"),
                                new DataColumn("Product"),
                                new DataColumn("Quantity")});
        dt.Rows.Add(101, "Sun Glasses", 5);
        dt.Rows.Add(102, "Jeans", 2);
        dt.Rows.Add(103, "Trousers", 12);
        dt.Rows.Add(104, "Shirts", 9);
        SendPDFEmail(dt);
    }
}
 
private void SendPDFEmail(DataTable dt)
{
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            string companyName = "ASPSnippets";
            int orderNo = 2303;
            StringBuilder sb = new StringBuilder();
            sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
            sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Order Sheet</b></td></tr>");
            sb.Append("<tr><td colspan = '2'></td></tr>");
            sb.Append("<tr><td><b>Order No:</b>");
            sb.Append(orderNo);
            sb.Append("</td><td><b>Date: </b>");
            sb.Append(DateTime.Now);
            sb.Append(" </td></tr>");
            sb.Append("<tr><td colspan = '2'><b>Company Name :</b> ");
            sb.Append(companyName);
            sb.Append("</td></tr>");
            sb.Append("</table>");
            sb.Append("<br />");
            sb.Append("<table border = '1'>");
            sb.Append("<tr>");
            foreach (DataColumn column in dt.Columns)
            {
                sb.Append("<th style = 'background-color: #D20B0C;color:#ffffff'>");
                sb.Append(column.ColumnName);
                sb.Append("</th>");
            }
            sb.Append("</tr>");
            foreach (DataRow row in dt.Rows)
            {
                sb.Append("<tr>");
                foreach (DataColumn column in dt.Columns)
                {
                    sb.Append("<td>");
                    sb.Append(row[column]);
                    sb.Append("</td>");
                }
                sb.Append("</tr>");
            }
            sb.Append("</table>");
            StringReader sr = new StringReader(sb.ToString());
 
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
 
                MailMessage mm = new MailMessage("sender@gmail.com""receiver@gmail.com");
                mm.Subject = "iTextSharp PDF";
                mm.Body = "iTextSharp PDF Attachment";
                mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "iTextSharpPDF.pdf"));
                mm.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.EnableSsl = true;
                NetworkCredential NetworkCred = new NetworkCredential();
                NetworkCred.UserName = "sender@gmail.com";
                NetworkCred.Password = "<password>";
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = NetworkCred;
                smtp.Port = 587;
                smtp.Send(mm);
            }
        }
    }
}
 

VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("OrderId"), New DataColumn("Product"), New DataColumn("Quantity")})
        dt.Rows.Add(101, "Sun Glasses", 5)
        dt.Rows.Add(102, "Jeans", 2)
        dt.Rows.Add(103, "Trousers", 12)
        dt.Rows.Add(104, "Shirts", 9)
        SendPDFEmail(dt)
    End If
End Sub
 
Private Sub SendPDFEmail(dt As DataTable)
    Using sw As New StringWriter()
        Using hw As New HtmlTextWriter(sw)
            Dim companyName As String = "ASPSnippets"
            Dim orderNo As Integer = 2303
            Dim sb As New StringBuilder()
            sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>")
            sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Order Sheet</b></td></tr>")
            sb.Append("<tr><td colspan = '2'></td></tr>")
            sb.Append("<tr><td><b>Order No:</b>")
            sb.Append(orderNo)
            sb.Append("</td><td><b>Date: </b>")
            sb.Append(DateTime.Now)
            sb.Append(" </td></tr>")
            sb.Append("<tr><td colspan = '2'><b>Company Name :</b> ")
            sb.Append(companyName)
            sb.Append("</td></tr>")
            sb.Append("</table>")
            sb.Append("<br />")
            sb.Append("<table border = '1'>")
            sb.Append("<tr>")
            For Each column As DataColumn In dt.Columns
                sb.Append("<th style = 'background-color: #D20B0C;color:#ffffff'>")
                sb.Append(column.ColumnName)
                sb.Append("</th>")
            Next
            sb.Append("</tr>")
            For Each row As DataRow In dt.Rows
                sb.Append("<tr>")
                For Each column As DataColumn In dt.Columns
                    sb.Append("<td>")
                    sb.Append(row(column))
                    sb.Append("</td>")
                Next
                sb.Append("</tr>")
            Next
            sb.Append("</table>")
            Dim sr As New StringReader(sb.ToString())
 
            Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
            Dim htmlparser As New HTMLWorker(pdfDoc)
            Using memoryStream As New MemoryStream()
                Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, memoryStream)
                pdfDoc.Open()
                htmlparser.Parse(sr)
                pdfDoc.Close()
                Dim bytes As Byte() = memoryStream.ToArray()
                memoryStream.Close()
 
                Dim mm As New MailMessage("sender@gmail.com""receiver@gmail.com")
                mm.Subject = "iTextSharp PDF"
                mm.Body = "iTextSharp PDF Attachment"
                mm.Attachments.Add(New Attachment(New MemoryStream(bytes), "iTextSharpPDF.pdf"))
                mm.IsBodyHtml = True
                Dim smtp As New SmtpClient()
                smtp.Host = "smtp.gmail.com"
                smtp.EnableSsl = True
                Dim NetworkCred As New NetworkCredential()
                NetworkCred.UserName = "sender@gmail.com"
                NetworkCred.Password = "<password>"
                smtp.UseDefaultCredentials = True
                smtp.Credentials = NetworkCred
                smtp.Port = 587
                smtp.Send(mm)
            End Using
        End Using
    End Using
End Sub
 
 
Screenshots
Email received with the PDF as attachment
Send Runtime generated file as Attachment in email in ASP.Net using C# and VB.Net
 
The generated PDF document
Send Runtime generated file as Attachment in email in ASP.Net using C# and VB.Net
 
 
Demo
 
 
Downloads