Programming Tutorials

How to Send Email in ASP.NET C# Using SMTP (Web.config Example)

How to Send Email in ASP.NET C# Using SMTP

Sending email is a common requirement in ASP.NET applications. You may need to send registration confirmations, contact-form messages, order notifications, password-reset links or other automated emails. In this tutorial, we will learn how to send email in ASP.NET using C# and SMTP, configure the mail server in Web.config, and send an email when a user clicks a button.

What you will learn: what SMTP is, how to configure SMTP settings in Web.config, how to use the C# MailMessage and SmtpClient classes, how to handle common errors, and what to consider when using Gmail or another email provider.

Advertisement

What is SMTP?

SMTP stands for Simple Mail Transfer Protocol. It is an application-layer protocol used to submit and transfer outgoing email. SMTP commonly uses TCP port 587 with STARTTLS for authenticated email submission, or port 465 for implicit TLS. Port 25 is commonly used for server-to-server mail transfer and may be blocked for application hosting.

In this example, we use the built-in .NET Framework classes System.Net.Mail. The SMTP server is configured in Web.config, so you do not need to repeat the server settings in every button-click event.

Advertisement

Step 1: Configure SMTP settings in Web.config

Open the Web.config file in your ASP.NET Web Forms project. Add the following system.net section inside the root configuration element. If a system.net section already exists, add the mail settings inside it instead of creating a duplicate section.

<configuration>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network
          host="smtp.gmail.com"
          port="587"
          enableSsl="true"
          userName="YOUR_EMAIL_ADDRESS"
          password="YOUR_SMTP_CREDENTIAL" />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

Replace the sample username and credential with the values supplied by your email provider. The example uses Gmail’s SMTP host and the submission port 587 with TLS. Provider requirements can change, so confirm the host, port, authentication method and sender restrictions in the provider’s current documentation.

Important Gmail note: A normal Gmail account password should not be used as an SMTP password. Depending on account type and eligibility, Google may require an app password (with 2-Step Verification enabled) or an approved relay/OAuth-based solution. Google Workspace administrators may configure SMTP relay. Do not assume that enabling “less secure apps” is an available or supported option.

Security recommendation: Do not commit real SMTP passwords or app passwords to a public repository. For production, store secrets in your hosting platform’s secret manager or another protected configuration source. If you must keep credentials in Web.config for a legacy application, restrict file access and consider protecting the configuration section using .NET Framework protected configuration.

Step 2: Add a button to your ASP.NET page

Add a button to your .aspx page. When the visitor clicks this button, the server-side click event will create the email and send it through the SMTP settings configured above.

<asp:Button
    ID="Button1"
    runat="server"
    Text="Send Email"
    OnClick="Button1_Click" />

Step 3: Write the C# code to send email

Open the code-behind file (for example, Default.aspx.cs). Add the System.Net.Mail namespace and write the following event handler. The SMTP server details are read from Web.config by SmtpClient when it is created without explicit host settings.

using System;
using System.Net.Mail;

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress(
                "YOUR_VERIFIED_SENDER@gmail.com");

            mail.To.Add("RECIPIENT@example.com");
            mail.Subject = "Test email from ASP.NET";
            mail.Body = "Hello! This is a test email sent from an ASP.NET application.";
            mail.IsBodyHtml = false;

            using (SmtpClient smtp = new SmtpClient())
            {
                // SMTP settings are read from Web.config.
                smtp.Send(mail);
            }
        }

        // Show a generic success message to the user.
        ScriptManager.RegisterStartupScript(
            this, GetType(), "mailSuccess",
            "alert('Email sent successfully.');", true);
    }
    catch (SmtpException)
    {
        // Log the detailed exception on the server.
        // Do not expose server details or credentials to visitors.
        ScriptManager.RegisterStartupScript(
            this, GetType(), "mailError",
            "alert('Email could not be sent. Please try again later.');", true);
    }
    catch (Exception)
    {
        // Log unexpected errors securely on the server.
        ScriptManager.RegisterStartupScript(
            this, GetType(), "generalError",
            "alert('Something went wrong. Please try again later.');", true);
    }
}

Change the sender and recipient addresses to valid addresses for your application. The sender should be verified or authorized by your SMTP provider. If your page does not use an ASP.NET UpdatePanel or ScriptManager, display the result using an appropriate server-side label or validation message instead.

Step 4: Understand the important C# mail settings

  • MailMessage: Creates the email message and holds its sender, recipient, subject and body.
  • From: Sets the sender address. Many providers require this address or its domain to be verified.
  • To: Adds one or more recipient addresses.
  • Subject: Sets the email subject line.
  • Body: Contains the message text or HTML.
  • IsBodyHtml: Set this to true only when the body contains trusted, properly encoded HTML.
  • SmtpClient: Sends the message using the SMTP configuration read from Web.config.

Step 5: Send an HTML email

If you want to send formatted HTML email, set IsBodyHtml to true and provide a valid HTML body. Do not insert untrusted user input directly into the HTML because it can create an injection or phishing risk. Encode user-supplied values before adding them to a message.

mail.Subject = "Welcome to our website";
mail.Body = "<h2>Welcome!</h2><p>Your registration is complete.</p>";
mail.IsBodyHtml = true;

Common SMTP errors and how to fix them

  • Authentication failed: Recheck the SMTP username and provider-approved credential. For Gmail, check whether an app password or an administrator-managed relay is required.
  • Could not connect to the remote server: Verify the SMTP host and port, and ask your hosting provider whether outbound SMTP connections are allowed.
  • STARTTLS is required: Check that the provider’s port and TLS settings match. Port 587 commonly uses STARTTLS.
  • Mailbox unavailable or relay denied: Confirm that the sender address is verified and that your account is permitted to send to the recipient.
  • Email is delivered to spam: Configure SPF and DKIM for your sending domain and publish a suitable DMARC policy. Use a consistent, authenticated sender domain.
  • Works locally but not on hosting: Hosting providers may block outbound SMTP or require you to use their relay or a transactional email provider.

Important security and production tips

  • Never publish SMTP passwords, app passwords or API keys in source code or public repositories.
  • Use TLS and follow your email provider’s current authentication instructions.
  • Validate recipient addresses and protect public forms against automated abuse.
  • Do not show raw exception messages, server paths or credentials to website visitors.
  • Use a queue and controlled retry strategy if the application sends a large volume of emails.
  • Monitor delivery, bounce and complaint information through your email provider.
  • For new .NET applications, consider a maintained email library such as MailKit or your provider’s official API/SDK. Microsoft documents SmtpClient as not recommended for new development.

Frequently asked questions

Which SMTP port should I use?

Use the port and encryption method specified by your provider. Port 587 with STARTTLS is a common authenticated submission setting; port 465 is commonly used with implicit TLS. Do not select a port without checking the provider’s instructions.

Can I use my normal Gmail password in Web.config?

No. Do not put your normal Google account password in an application. Use an authentication method supported for your account, such as an app password where eligible, Google Workspace SMTP relay or an approved OAuth-based integration.

Why does the email work on localhost but fail on the server?

The hosting environment may block outbound SMTP, use a firewall rule, or require a different relay. Check the host and port, provider authentication requirements and hosting support documentation.

Is this code suitable for modern .NET?

This example is intended for legacy ASP.NET Web Forms applications running on .NET Framework. For new ASP.NET Core or modern .NET projects, use a maintained email library or a transactional email provider’s API/SDK, with secure secret storage and asynchronous sending where supported.

Conclusion

In this tutorial, we covered how to send email in ASP.NET C# using SMTP, configure the mail server in Web.config and send an email from a button-click event. We also reviewed HTML email, common SMTP errors and important security practices. The example is useful for understanding a legacy Web Forms application; for production and new projects, always follow your provider’s current authentication guidance and protect all email credentials.

Read more tutorials

RochakGuy

Hi, I'm Piyush and I'm a passionate blogger. I love sharing my insights on Rochaksite.com. I'm committed to providing practical and informative content that helps readers achieve their goals and make informed decisions. When I'm not writing, I enjoy exploring new topics and trends in Technology and indulging in my personal hobbies and interests.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button