Now a days it is very common to send mail in every web application. For example, sending mail to customer about new products or any updates happens in websites. Microsoft .Net provides us two namespaces System.Net and System.Net.Mail to send mail from our website.

So, this blog will explain you how to send mail in asp.net c# using Gmail SMTP server. It also demonstrate, how to send plain text, HTML body, attachment in email and send email with CC and BCC. To implement this code you must have a valid email account.

Namespaces

Most importantly remember that, while you’re sending email using .Net you have to add these two namespaces at the top of page.

using System.Net;

using System.Net.Mail;

Sending only plain text in email

To understand mailing code properly I have created a form with 3 fields "To email address", "Subject" and "Body". Clicking on send button will take body, subject from form and send it to your provided email address. Check out below code.

SendPlainText.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SendPlainText.aspx.cs" Inherits="SendPlainText" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Sending only plain text in email</title>

    <style type="text/css">

        input[type=text] {

            width: 90%;

            height: 20px;

            font-family: sans-serif;

        }

        textarea {

            resize: none;

            font-family: sans-serif;

        }

        table {

            display: table;

            margin: 0px auto;

        }

        h2 {

            display: table;

            margin: 40px auto 25px;

        }

        td {

            padding-bottom: 10px;

            padding-right: 10px;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

        <h2>Sending only plain text in email</h2>

        <table>

            <tr>

                <td>To:

                </td>

                <td>

                    <asp:TextBox ID="txtToEmailAddress" runat="server" />

                </td>

            </tr>

            <tr>

                <td>Subject:

                </td>

                <td>

                    <asp:TextBox ID="txtSubject" runat="server" />

                </td>

            </tr>

            <tr>

                <td>Body:

                </td>

                <td>

                    <asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Rows="8" Columns="35" />

                </td>

            </tr>

            <tr>

                <td>&nbsp;

                </td>

                <td>

                    <asp:Button ID="btnSend" Text="Send" runat="server" OnClick="btnSend_Click" />

                </td>

            </tr>

            <tr>

                <td colspan="2">

                    <asp:Label ID="lblMsg" Text="Mail sent successfully. Check your mail box." runat="server" />

                </td>

            </tr>

        </table>

    </form>

</body>

</html>

SendPlainText.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net; /* Add this Namespace */

using System.Net.Mail; /* Add this Namespace */

  

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

  

    }

    /* Send button click event */

    protected void btnSend_Click(object sender, EventArgs e)

    {

        using (MailMessage mail = new MailMessage())

        {

            mail.Subject = txtSubject.Text;

            mail.Body = txtBody.Text;

            mail.From = new MailAddress("FromEmailAddress@gmail.com", "Diplay name in email");

            mail.To.Add(new MailAddress(txtToEmailAddress.Text));

            SmtpClient smtp = new SmtpClient();

            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

            smtp.EnableSsl = true;

            smtp.Host = "smtp.gmail.com";

            smtp.Port = 587;

            smtp.UseDefaultCredentials = true;

            NetworkCredential NetworkCred = new NetworkCredential("FromEmailAddress@gmail.com", "FromEmailAddress Password");

            smtp.Credentials = NetworkCred;

            smtp.Send(mail);

            lblMsg.Text = "Mail sent successfully. Check your mail box.";

        }

    }

}

Output

Sending email with CC and BCC

To send email to multiple recipients you can use CC (Carbon Copy) or BCC (Blind carbon copy). In this this example, add two textboxes for cc and bcc. Mailing code will be change little bit which is given below. We have to use mm.To.Add() and mm.Bcc.Add() functions.

protected void btnSend_Click(object sender, EventArgs e)

{

    using (MailMessage mail = new MailMessage())

    {

        mail.Subject = txtSubject.Text;

        mail.Body = txtBody.Text;

        mail.From = new MailAddress("FromEmailAddress@gmail.com", "Diplay name in email");

        mail.To.Add(new MailAddress(txtToEmailAddress.Text));

        mail.CC.Add(new MailAddress(txtCCEmailAddress.Text)); /* Add tihs to send email to CC */

        mail.Bcc.Add(new MailAddress(txtBCCEmailAddress.Text)); /* Add tihs to send email to BCC */

        SmtpClient smtp = new SmtpClient();

        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

        smtp.EnableSsl = true;

        smtp.Host = "smtp.gmail.com";

        smtp.Port = 587;

        smtp.UseDefaultCredentials = true;

        NetworkCredential NetworkCred = new NetworkCredential("FromEmailAddress@gmail.com", "FromEmailAddress Password");

        smtp.Credentials = NetworkCred;

        smtp.Send(mail);

        lblMsg.Text = "Mail sent successfully. Check your mail box.";

    }

}

Output

Sending email with HTML body

To send HTML tags in email body we have to set mail.IsBodyHtml = true. In this example I have used static html body. See my code to understand it properly.

protected void btnSend_Click(object sender, EventArgs e)

{

    using (MailMessage mail = new MailMessage())

    {

        mail.Subject = txtSubject.Text;

        mail.Body = "<div style='display: table; margin: auto;'>" +

                        "<h2>HTML Email</h2>" +

                        "<b>This is b tag.</b>" +

                        "<p>" + txtBody.Text + "</p>" +

                    "</div>"; /* HTML body */

        mail.IsBodyHtml = true; /* Set IsBodyHtml = true to send html in email */

        mail.From = new MailAddress("FromEmailAddress@gmail.com", "Diplay name in email");

        mail.To.Add(new MailAddress(txtToEmailAddress.Text));

        SmtpClient smtp = new SmtpClient();

        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

        smtp.EnableSsl = true;

        smtp.Host = "smtp.gmail.com";

        smtp.Port = 587;

        smtp.UseDefaultCredentials = true;

        NetworkCredential NetworkCred = new NetworkCredential("FromEmailAddress@gmail.com", "FromEmailAddress Password");

        smtp.Credentials = NetworkCred;

        smtp.Send(mail);

        lblMsg.Text = "Mail sent successfully. Check your mail box.";

    }

}

Output

Sending email with an attachment

To send an email with attachment you have to put FileUpload control in your .aspx file. There must be some change in code. Please check out my code. To add attachment we have to use mail.Attachments.Add() function. 

protected void btnSend_Click(object sender, EventArgs e)

{

    using (MailMessage mail = new MailMessage())

    {

        mail.Subject = txtSubject.Text;

        mail.Body = txtBody.Text;

        mail.From = new MailAddress("FromEmailAddress@gmail.com", "Diplay name in email");

        mail.To.Add(new MailAddress(txtToEmailAddress.Text));

        /* Attachment code */

        if (fileAttachment.HasFile)

        {

            mail.Attachments.Add(new Attachment(fileAttachment.PostedFile.InputStream, fileAttachment.FileName));

        }

        SmtpClient smtp = new SmtpClient();

        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

        smtp.EnableSsl = true;

        smtp.Host = "smtp.gmail.com";

        smtp.Port = 587;

        smtp.UseDefaultCredentials = true;

        NetworkCredential NetworkCred = new NetworkCredential("FromEmailAddress@gmail.com", "FromEmailAddress Password");

        smtp.Credentials = NetworkCred;

        smtp.Send(mail);

        lblMsg.Text = "Mail sent successfully. Check your mail box.";

    }

}

Attachment file from internal folder of project

Above attachment code basically take file from original location. But if you want to take file from any internal folder of your project than save file first in folder. Create a folder “Uploads” in your project and change only file attachment code like given below,

if (fileAttachment.HasFile)

{

    fileAttachment.SaveAs(Server.MapPath("~/Uploads/") + fileAttachment.FileName);

    mail.Attachments.Add(new Attachment(Server.MapPath("~/Uploads/") + fileAttachment.FileName));

}

Output

5.5.1 Authentication Required error

While working with email code first time, it is common to have 5.5.1 Authentication Required error if you are using Gmail SMTP server. This error occurs because Gmail does not allow third party website or application to access your gmail account.

To solve this error you have to change Gmail settings and allow your account to send email from website or application. Go to www.google.com/settings/security/lesssecureapps and turn on the option.

Hope this blog will help you. If I missed something or you have doubts comment below. Thank you..!!