Home » Web Development » Sending Email Through GMAIL using C# and ASP.NET

Sending Email Through GMAIL using C# and ASP.NET

Difficulty Level    

We need to create two pages. One will be the the page with the code(class file) and the other will be the HTML page

Step 1: create a new class file called email.aspx.cs
Here’s the code.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page


protected void Page_Load(object sender, EventArgs e)


protected void btnSend_Click(object sender, EventArgs e)

MailMessage mm = new MailMessage();
SmtpClient smtp = new SmtpClient();
mm.From = new MailAddress(txtFrom.Text);
mm.To.Add(new MailAddress(txtTo.Text));
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
mm.IsBodyHtml = true;

smtp.Host = “smtp.gmail.com”; //You can add this in the webconfig
smtp.EnableSSL = true;

System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = “user@gmail.com”;
NetworkCred.Password = “gmailpassword”;

smtp.UseDefaultCredentials = true;

smtp.Credentials = NetworkCred;

smtp.Port = 587; //this is Gmail port for e-mail if you are using google apps and SSL is off the port is 465

smtp.Send(mm);//send an e-mail


Step 2: Create a new aspx file called email.aspx

<%@ Page Language=”C#” CodeFile=”email.aspx.cs” title=”Untitled” %>





That’s It!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.