Minifycode 2020-01-13 Viewed 1.7K times C#

The following C# source code shows how to send an email with an attachment from a Gmail address . The Gmail SMTP server name is and the port using send mail is 587 . Here using NetworkCredential for password based authentication.

public static string sendMail(string To, string Subject, string Body, string Attachments, string Filename)
             Attachments = "The following C# source code shows how to send an email with an attachment from a 
             Gmail or other address . The Gmail SMTP or other server name is, or other 
             smpt and the port using send mail is 587 . Here using Network Credential for password based authentication.";
             string result = "Message Sent Successfully..!!";
                string UserID = "";
                string Password = "password";
                //Initializes a new SmtpClient.
                SmtpClient client = new SmtpClient("", 587);
                client.EnableSsl = true;
                client.Credentials = new System.Net.NetworkCredential(UserID, Password);
                MailMessage msg = new MailMessage(UserID, To);
                msg.IsBodyHtml = true;
                msg.Subject = Subject;
                msg.Body = Body;
                if (!string.IsNullOrEmpty(Attachments))
                    var memStream = new MemoryStream(GetPDF(Attachments));
                    memStream.Position = 0;
                    var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
                    var reportAttachment = new Attachment(memStream, contentType);
                    reportAttachment.ContentDisposition.FileName = Filename;
            catch (Exception ex)
                result = "Error";
            return result;
        public static byte[] GetPDF(string pHTML)
            byte[] bPDF = null;

            MemoryStream ms = new MemoryStream();
            TextReader txtReader = new StringReader(pHTML);

            // 1: create object of a itextsharp document class  
            Document doc = new Document(PageSize.A4, 25, 25, 25, 25);

            // 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file  
            PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);

            // 3: we create a worker parse the document  
            HTMLWorker htmlWorker = new HTMLWorker(doc);

            // 4: we open document and start the worker on the document  

            // 5: parse the html into the document  

            // 6: close the document and the worker  

            bPDF = ms.ToArray();

            return bPDF;


How to send HTML-formatted email?

Now I want to send HTML-Formatted email using the following method that I wrote for sending emails.

Note: Setting isBodyHtml to true allows you to use HTML tags in the message body.

MailAddress addressFrom = new MailAddress("", "Minifycode");
MailAddress addressTo = new MailAddress("");
MailMessage message = new MailMessage(addressFrom, addressTo);

message.Date = DateTime.Now;
message.Subject = "Sending Email with HTML Body";
string htmlString = @"<html>
                      <p>Thank you for your mail.</p>
message.BodyHtml = htmlString;

SmtpClient client= new SmtpClient();
client.Host = "";
client.Port = 587;
client.Username = addressFrom.Address;
client.Password = "password";
client.ConnectionProtocols = ConnectionProtocols.Ssl;

Console.WriteLine("Message Sent Successfully!");

How to send email with attachment from C#, how to send HTML-formatted email?
C# is a programming language developed by Microsoft that runs on the .NET Framework. C# is used to develop web, desktop, mobile, games and much more application. C# is a object-oriented programming language developed by Microsoft within its .NET Framework. Led by Anders Hejlsberg, your basic C# programming and will also take you through various advanced concepts related to C# programming language. C# such as control statements, objects and classes, inheritance, constructor, destructor, this, static, sealed, polymorphism, abstraction, abstract class, interface, File IO, Collections, namespace, encapsulation, properties, indexer, arrays, strings, regex, exception handling, multithreading etc. For example... using System; namespace MinifyCode { class Program { static void Main(string[] args) { Console.WriteLine("Hello Minify Code"); } } } Output: Hello Minify Code In this article you will learn, what is server side controls. We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object, and the Response object. Session Application Cache Request Response Server User Trace Server Object The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform many type of jobs. Methods and Properties of the Server object The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; using System.Data.Entity; namespace minifycode { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Initialize the product database. Database.SetInitializer(new ProductDatabaseInitializer()); // Create custom role and user. RoleActions roleActions = new RoleActions(); roleActions.AddUserAndRole(); // Add Routes. RegisterCustomRoutes(RouteTable.Routes); } void RegisterCustomRoutes(RouteCollection routes) { routes.MapPageRoute( "ProductsCategoryRoute", "Category/{categoryName}", "~/ProductList.aspx" ); routes.MapPageRoute( "ProductNameRoute", "Product/{productName}", "~/ProductDetails.aspx" ); } } }