How to send mail in asp net c# with example

Here's an example of how to send an email using ASP.NET C#:

Step 1: Create a new ASP.NET Web Application

Create a new ASP.NET Web Application project in Visual Studio. Name it, for example, "EmailSender".

Step 2: Add a reference to System.Net.Mail

In the Solution Explorer, right-click on the project and select "Add Reference". Browse to the "Assemblies" folder and select "System.Net.Mail". This will add the necessary namespace for sending emails.

Step 3: Create a new class for sending emails

Create a new class in the App_Code folder (or any other folder of your choice) and name it, for example, "EmailSender.cs". Add the following code:

using System.Net.Mail;
using System.Net;

public class EmailSender
{
    public void SendEmail(string toEmail, string subject, string body)
    {
        // Create a new MailMessage object
        MailMessage mail = new MailMessage();

        // Set the sender's email address
        mail.From = new MailAddress("[email protected]");

        // Set the recipient's email address
        mail.To.Add(toEmail);

        // Set the subject of the email
        mail.Subject = subject;

        // Set the body of the email
        mail.Body = body;

        // Create a new SmtpClient object
        SmtpClient client = new SmtpClient();

        // Set the SMTP server's address and port
        client.Host = "your-smtp-server.com";
        client.Port = 587;

        // Set the SMTP server's username and password
        client.Credentials = new NetworkCredential("your-smtp-username", "your-smtp-password");

        // Send the email
        client.Send(mail);
    }
}

Step 4: Use the EmailSender class in your ASP.NET page

Create a new ASP.NET page (e.g., "Default.aspx") and add the following code:

using System;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a new EmailSender object
        EmailSender emailSender = new EmailSender();

        // Set the email details
        string toEmail = "[email protected]";
        string subject = "Test Email";
        string body = "This is a test email sent from ASP.NET C#";

        // Send the email
        emailSender.SendEmail(toEmail, subject, body);
    }
}

Step 5: Run the application

Run the application by pressing F5 or clicking the "Run" button in Visual Studio. The email should be sent to the recipient's email address.

Note: Make sure to replace the placeholders (e.g., "[email protected]", "your-smtp-server.com", "your-smtp-username", and "your-smtp-password") with your actual email address, SMTP server, and credentials.

This is a basic example of how to send an email using ASP.NET C#. You can customize the email sender class to fit your specific needs, such as adding attachments or customizing the email body.