Sending emails are required in every web-application, so in one of the previous article, I have provided code to send email using C# in ASP.NET MVC, now in this article, I have provided code to send email in ASP.NET web-form using C#, with or without attachment in email.

Step1: Create a new project in your Visual Studio, by navigating to File-> New Project -> Web ( from the left-pane) and "Web-Application" from right-pane, name the project and click OK.

In the next screen, select "Empty" project and also check "Web-Form", then click "OK"

send-mail-in-asp-net-c-sharp-min.png

Step 2: Create a new .aspx web-form page and name it "Default.aspx".

Right-click on your project name and then Select "Add"-> "New Item"-> "Web-Form" -> name it "Default.aspx" and click "OK"

web-form-add-send-email-min.png

We will be adding a button control in the above web-form page to send email on button click, here is the complete web-form code after adding "Button" control and 3  "Textbox" control, using which we will send "Subject", "Email Address" to which we need to send email, and a "Textbox" which contains content of Email.( Email message )

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SendEmailASPNET.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            To:<br/>
         <asp:TextBox ID="To" runat="server"></asp:TextBox>
         </div>
        <div>
            Subject:<br/>
         <asp:TextBox ID="Subject" runat="server"></asp:TextBox>
            </div>
        <div>
            Message:<br/>
           <asp:TextBox ID="EmailMessage" runat="server" TextMode="MultiLine" Height="99px"></asp:TextBox>
         </div>
        <div>
            <asp:Button ID="Button1" runat="server" Text="Send Mail" OnClick="SendEmail" />
        </div>
    </form>
</body>
</html>

Step 3: Add C# code to send email without attachment on button click in Default.aspx.cs file

using System;
using System.Net.Mail;
namespace SendEmailASPNET
{
    public partial class Default : System.Web.UI.Page
    {
      
        protected void SendEmail(object sender, EventArgs e)
        {
            //Send Email
            MailMessage Msg = new MailMessage();
            Msg.From = new MailAddress("senderEmailId@gmail.com", "Sender Name");// Sender details here, replace with valid value
            Msg.Subject = Subject.Text; // subject of email
            Msg.To.Add(To.Text); //Add Email id, to which we will send email
            Msg.Body = EmailMessage.Text;
            Msg.IsBodyHtml = true;
            Msg.Priority = MailPriority.High;
            SmtpClient smtp = new SmtpClient();
            smtp.UseDefaultCredentials = false; // to get rid of error "SMTP server requires a secure connection"
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.Credentials = new System.Net.NetworkCredential("senderEmailId@gmail.com", "password");// replace with valid value
            smtp.EnableSsl = true;
            smtp.Timeout = 20000;

            smtp.Send(Msg);
        }
    }
}

In the above code, we are creating a MailMessage in C# and adding Subject,To details of the email.

Using SmtpClient we are specifying host and Enabling SSL, usually port of sending emails using gmail account is 587.

The SmtpClient class is responsible for sending the email. The configuration of the SmtpClient object is often the place where most email sending errors occur, so it is important to ensure that you use the right settings.

Note: When you set EnableSsl to true, you actually switch TLS on, which is required for port 587. Https is not supported by the SmtpClient object. For more details, read the Remarks section of the docs on MSDN.

That's it, we are done.

Build and run project in your browser, you will see output as below

send-email-in-asp-net-csharp-min.png

Note: You might get error "'The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.'" To get rid of it, we are using " smtp.UseDefaultCredentials = false; " but you might have to Enable Less Secure apps or if you have already enabled 2-Step Verification you would have to disable it.
If you don't want to disable 2-Step Verification add app password in your gmail account and use that password in C# code.

Once you will click "Send Mail" button, it will call code bhind C# code, and will send email, I tried it and received the email.

email-received-using-asp-net-min.png

Adding Attachment in your email in C#

To add attachment in your emai,  you need to upload file on server in asp.net.

Once you do it, simply add complete path of file and add as an attachment in C# Email as below

Attachment data = new Attachment("PATH_TO_YOUR_FILE");

// your path may look like Server.MapPath("~/yourfile.png")
Msg.Attachments.Add(data);

You may also like to read:

Send Email in ASP.NET MVC (With or Without Attachment)

Verify email address exists or not? (With email id validation in C#)