Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Tools
    • Json Beautifier
    • Html Beautifier
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
03 Oct
2020

Send Email With HTML Template And PDF Using ASP.Net C#

by Shubham Batra

2568

Step 1 : Create a project
 Add two DLL File in your project from Nuget.org


Step 2 :Add Appsettings into webconfig file 
 <appSettings>
		<add key="Host" value="smtp.gmail.com" />
		<add key="EnableSsl" value="true" />
		<add key="UserName" value="[email protected]" />
		<add key="Password" value="Enteryourpassword" />
		<add key="Port" value="587" />
</appSettings>
Step : 3 add a namespace into email.aspx.cs
using System.Web;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.pdf.draw;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.xml;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.pipeline.css;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.html;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.html;
Step : 4 Complete code of email with html template and attachment of pdf  
 protected void Page_Load(object sender, EventArgs e)
    {

        //string emailaddress = "[email protected]"; string ZipCode,
        string EmailFirstName = "Shubham";
        string EmailLastName = "Batra";
        string EmailPaymentTransactionId = "[email protected]";
        string EmailCreatedOn = DateTime.Now.ToString("dd/MM/yyyy");
        string Emailemailaddress = "shubhambatra1994 @gmail.com";
        string EmailAmount = "[email protected]";
        string FullName = "Shubham Batra";
        string PracticeLogo = HttpContext.Current.Server.MapPath("/code2night.png");

        try
        {
            string recepientEmail = "[email protected]";
            string body = string.Empty;
            using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/HtmlPage.html")))
            {
                body = reader.ReadToEnd();
            }
            using (MailMessage mailMessage = new MailMessage())
            {
                // convert html to pdf 
                string strHtml = string.Empty;
                //HTML File path  
                string htmlFileName2 = HttpContext.Current.Server.MapPath("~/HtmlPageforpdf.html");
                //Image file path.
                string imging = "";
                if (PracticeLogo != "")
                {
                    imging = PracticeLogo;
                }
                //reading html code from html file
                FileStream fsHTMLDocument = new FileStream(htmlFileName2, FileMode.Open, FileAccess.Read);
                StreamReader srHTMLDocument = new StreamReader(fsHTMLDocument);
                strHtml = srHTMLDocument.ReadToEnd();
                srHTMLDocument.Close();
                strHtml = strHtml.Replace("\r\n", "");
                strHtml = strHtml.Replace("\0", "");
                strHtml = strHtml.Replace("(EmailFirstName)", FullName);
                strHtml = strHtml.Replace("(EmailAmount)", EmailAmount);
                strHtml = strHtml.Replace("(EmailPaymentTransactionId)", EmailPaymentTransactionId);
                strHtml = strHtml.Replace("(EmailCreatedOn)", EmailCreatedOn);
                strHtml = strHtml.Replace("(imging)", imging);
                //TestPDF.HtmlToPdfBuilder builder = new TestPDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
                //TestPDF.HtmlPdfPage first = builder.AddPage();
                //first.AppendHtml(strHtml);
                // byte[] filingpdf = builder.RenderPdf();

                // second method

                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(strHtml))
                    {
                        //Set factories
                        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                        htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                        //Set css
                        ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                        cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/NewCSS/Clientdetail.css"), 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();
                }

                // send email and replace text file 
                body = body.Replace("{Logosendwithemail}", "companyLogo");
                body = body.Replace("{EmailFirstName}", FullName);
                body = body.Replace("{EmailAmount}", EmailAmount);
                body = body.Replace("{EmailPaymentTransactionId}", EmailPaymentTransactionId);
                body = body.Replace("{EmailCreatedOn}", EmailCreatedOn);
                byte[] reader = { };
                if (PracticeLogo != "")
                {
                    reader = File.ReadAllBytes( PracticeLogo);
                   
                    MemoryStream image1 = new MemoryStream(reader);
                    AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, System.Net.Mime.MediaTypeNames.Text.Html);
                    LinkedResource headerImage = new LinkedResource(image1, System.Net.Mime.MediaTypeNames.Image.Jpeg);
                    headerImage.ContentId = "companyLogo";
                    headerImage.ContentType = new ContentType("image/jpg");
                    av.LinkedResources.Add(headerImage);
                    mailMessage.AlternateViews.Add(av);
                    ContentType mimeType = new System.Net.Mime.ContentType("text/html");
                    AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
                }
                mailMessage.IsBodyHtml = true;
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]);
                mailMessage.Subject = "You Are Registered Successfully!";
                mailMessage.Body = body;
                mailMessage.IsBodyHtml = true;
                mailMessage.Attachments.Add(new Attachment(new MemoryStream(bytesArray), "receipt.pdf"));
                mailMessage.To.Add(new MailAddress(recepientEmail));
                SmtpClient smtp = new SmtpClient("smtp.gmail.com");
                smtp.Host = ConfigurationManager.AppSettings["Host"];
                smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
                System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
                NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = NetworkCred;
                smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
                smtp.Send(mailMessage);

            }
        }

        catch (Exception ex)
        {

        }
    }
Step 5 : Add new html file 
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Appointment Confirmed</title>



    <style>
        /*-- fonts --*/
        @import url('https://fonts.googleapis.com/css2?family=Roboto:[email protected]&display=swap');

        div, p, h1, h2, h3, h4, ol, li, ul {
            font-family: 'Roboto', 'sans-serif';
        }
        /*-- fonts --*/
        body {
            margin: 0;
            padding: 0;
        }

        body, * {
            font-family: 'Roboto', 'sans-serif';
            box-sizing: border-box;
        }




        .bitmap {
            width: 236px;
            height: 56px;
        }

        .body {
            width: 600px;
            height: 734px;
            background-color: #F4F5F5;
            text-align: center;
            margin: 0 auto;
            padding: 50px 0 0;
        }

        .rectangle {
            background-color: #FFFFFF;
            border-radius: 16px;
            box-shadow: 0 2px 4px 0 rgba(52, 61, 86, 0.04), 0 16px 32px 0 rgba(52, 61, 86, 0.2);
            width: 504px;
            /*height: 446px;*/
            height: auto;
            text-align: center;
            margin: 48px auto 32px;
            padding: 40px;
        }

        .hi-nikita {
            color: #343D56;
            font-size: 12px;
            /*font-weight: 900;*/
            line-height: 14px;
            font-family: 'Roboto';
            font-weight: bold;
        }

        .thanks-for-your-paym {
            color: #031926;
            font-size: 20px;
            /*font-weight: 400;*/
            font-weight: bold;
            letter-spacing: -0.25px;
            line-height: 24px;
            font-family: 'Roboto';
            margin: 10px 0 40px;
        }

        .amount-paid {
            color: #343D56;
            font-size: 12px;
            /*font-weight: 400;*/
            font-weight: bold;
            line-height: 14px;
            font-family: 'Roboto';
        }

        .ammount {
            color: #031926;
            font-size: 15px;
            /*font-weight: 400;*/
            font-weight: bold;
            line-height: 38px;
            font-family: 'Roboto';
            margin: 10px 0 35px;
        }

        .confirmation-number {
            color: #343D56;
            font-size: 12px;
            /*font-weight: 400;*/
            font-weight: bold;
            line-height: 14px;
            font-family: 'Roboto';
        }

        .confnumber {
            color: #031926;
            font-size: 20px;
            /*font-weight: 400;*/
            font-weight: bold;
            line-height: 24px;
            font-family: 'Roboto';
            margin: 10px 0 35px;
        }

        .date {
            color: #343D56;
            font-size: 12px;
            /*font-weight: 400;*/
            font-weight: bold;
            line-height: 14px;
            font-family: 'Roboto';
        }

        .may-20th-2020 {
            color: #031926;
            font-size: 20px;
            /*font-weight: 400;*/
            font-weight: bold;
            line-height: 24px;
            font-family: 'Roboto';
            margin-top: 8px;
        }

        .you-have-received-th {
            color: #343D56;
            font-size: 11px;
            /*font-weight: 400;*/
            font-weight: bold;
            line-height: 15px;
            width: 452px;
            text-align: center;
            margin: 0 auto;
        }

            .you-have-received-th a {
                color: #343D56;
                font-family: 'Roboto';
            }
    </style>
</head>
<body>
    <div class="body">
        <img src="cid:{Logosendwithemail}" alt="Logo" class="bitmap" />


        <div class="rectangle">
            <div class="hi-nikita">Hi, {EmailFirstName}!</div>
            <div class="thanks-for-your-paym">Welcome You Too Code2night.com!</div>
            <div class="amount-paid">Your Account Email Id</div>
            <div class="ammount">{EmailAmount}</div>
            <div class="confirmation-number">Your Account Password</div>
            <div class="confnumber">{EmailPaymentTransactionId}</div>
            <div class="date">Date</div>
            <div class="may-20th-2020">{EmailCreatedOn}</div>
            <a style="color: #22BCE5" href="{Url}"></a><br />
        </div>
        <div class="you-have-received-th">
            You have received this mail because you have paid for dental services at sedadental.com. You can always unsubscribe from our mailing list, by clicking on Unsubscribe. You can also reply to this message, including <a href="http://localhost:45905/shubham/4/Chrysanthemum.jpg"> unsubscribe </a> in the topic.
        </div>
    </div>
</body>
   

</html>
Step 6 : add new html file for send pdf 
<html>

<body>
    <div class="body">
        <img src="(imging)" alt="Logo" class="bitmap" style="width: 236px;height: 56px;" />

        <div class="rectangle_outer">
            <div class="rectangle">
                <div class="hi-nikita">Hi, (EmailFirstName)!</div>
                <div class="thanks-for-your-paym">Thanks For Your Payment!</div>
                <div class="amount-paid">Ammount Paid</div>
                <div class="ammount">$(EmailAmount)</div>
                <div class="confirmation-number">Confirmation Number</div>
                <div class="confnumber">(EmailPaymentTransactionId)</div>
                <div class="date">Date</div>
                <div class="may-20th-2020">(EmailCreatedOn)</div>
                <a style="color: #22BCE5" href="(Url)"></a><br />
            </div>
        </div>
        
    </div>
</body>
</html>
Step : 7  Final output 


  • |
  • Send Email With HTML Template And PDF Using ASPNet C# , Send Email , Email with html template , email with pdf attachment , email with html and pdf

Comments

Tags

How to set Date and time format in IIS Manager
IIS Manager
IIS
Internet Information Services (IIS) Manager
Internet Information Services (IIS)
Internet Information Services
Error Handling In AspNet Core
Exception Handling Asp Net Core
Exception Handling
Exception Handling Asp Net
Aspnet
Creating Log Files in MVC
Error Handling in MVC
Exception Handling in AspNet
Handling Exceptions and Creating Error Logs in Asp net Mvc using base controller
net
Code2Tonight
Stopping Browser Reload On Save
Repository Pattern with ADONet in MVC
Repository Pattern With ASPNET MVC And AdoNet
MVC Crud Operation
Jquery Full Calender Integrated With ASPNET
Full Calendar
Jquery Calendar
Slick Slider
Slick Slider Example
responsive carousels
Entity Framework
MVC
Intergrate SummerNote Text Editor into AspNet MVC
Web Config
Auto Redirection
Redirection from Http to https
AspNet
Url Rewriting
Postgre
PgAdmin4
PostgreSql
A Non Fatal Error Occured During Cluster Initialisation In Postgre SQL
Microsoft Outlook
Outlook Appointments
Microsoft Exchange Service
Send Email With HTML Template And PDF Using ASPNet C#
Send Email
Email with html template
email with pdf attachment
email with html and pdf
Microsoft Outlook Contacts
Outlook
Microsoft Exhchange Service
JSON
Convert string with dot notation to JSON
HTTP Error 5025 ANCM Out Of Process Startup Failure
Internet Information Service
Net core
Payumoney Integration With AspNet MVC
Prism js
Highlighting Syntax
Syntax Highlighting
code stylings
c#
Jquery AJax
Ajax
Jquery
Implement Stripe Payment Gateway In ASPNET
Using Checkout in an ASPNET Web Forms application
Stripe Payment
Stripe Payment Integration
Stripe Integeration
How to upload Image file using AJAX andjQuery
upload Image file using AJAX and jquery
Ajax call
file upload using ajax
file uploading using ajax and jquery
ConfigurationBuilder does not contain a definition for SetBasePath
Reading app json file in dot net core
Appsetting jso
Dot Net Core
Globalization and localization in ASPNET Core
Asp Net Core with Resource file resx
How to get the resx file strings in asp net core
Culture in Net core
Localisation in AspNet Core
Url Encryption in AspNet MVC
Url Encryption in C#
Url Encryption
Custom Helpers
Slick Slider with single slide
Slick
Vue js
Child Components
How to reload vue js child components
Net Core
Visual Studio
C#
Net core 31
Razor
Zoom sdk
Zoom c# wrapper Inegration
zoom Integration in c#
Zoom Integration
Zoom window sdk
vue js toggle button
vue js
toggle buttons
vuejs
vue js toggle switch
SignalR
VueJs
SignalR in Net Core
Chat App in Vue js
Chat App using SignalR
AspNet Chat app
JPlayer
Html5 Audio Video Player
Music Player
QR Code Generator
QR Code
Jquery QR Code
AspNet MVC
Google Maps
Google map api
Places API
Google map Places API in AspNet
Jquery Autocomplete
Autocomplete
Jquery UI Autocomplete
ExcelDataReader
Import data from excel in AspNet
Card Number Formatting
Amex Card Format
Card Format
FCM
Cloud Messaging
Android Notifications
FCM Notifications for IOS
IOS Notifications
Angular js
apply css on child components in Angular js
Angular Mentions
Google Sign In
Google Login
Google Oauth Api
Social Login
Aspnet Mvc
Google + Api
Create and publish a package using Visual Studio (NET Framework
Windows)
Create and publish a nuget package
create your own nuget package
Image compress
Image optimization
compress Image
optimize Image
WebForm
AspNet Web Pages
Batch Script
Database backup
Powershell
ASpNet
Sql Server Backup
LinkedIn Authentication
Login using LinkedIN
Social Login in AspNet
LinkedIn Authentication in AspNet MVC
LinkedIn Login in aspnet MVC
Shuffle List in c#
C#Net
Google Login in AspNet MVC
GoogleAuthentication Nuget package
Password Encryption
RFC Encryption
Encryption and Decryption
Encryption in AspNet
Base 64 Encryption
Base 64 Decryption

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Kurukshetra
  • [email protected]

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2022 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Json Beautifier