How to Send Email in Asp.Net using C# and VB

← PrevNext →

Last update: 25th August 2022

The SmtpClient() class in .Net, provides necessary functions to send emails across the web. It is one of most popular method for sending e-mails in Asp.Net. It uses SMTP (Simple Mail Transfer Protocol). I am sharing a simple example here that explains how easily you can send emails from your Asp.Net application. The codes are in C# and VB.

Some important properties, which I am going to cover in this article, are Host, UseDefaultCredentials and DeliveryMethod.

Send Email in Asp.Net using SmtpClient() Method

SMTP stands for Simple Mail Transfer Protocol.

Also Read: How to send emails in Asp.Net C# using Hotmail SMTP mail server

The Markup

In the markup section, add a button. The buttons click event will call a code behind procedure called "sendEmail".

<!DOCTYPE html>
<html>
<head>
    <title>Send Email in Asp.Net</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input type="button" id="send" value="Send Email" 
                onserverclick="sendEmail" runat="server" />
        </div>
    </form>
</body>
</html>
Code Behind (C#)
using System;

public partial class _Default : System.Web.UI.Page 
{
    protected void sendEmail(object sender, EventArgs e)
    {
        string sSubject = "Welcome to encodedna.com";       // The subject line.
        string sBody = "Body of the e-mail.";       // Email body.

        // You can add style to the body content. For example...
        sBody = "<div style=border:solid 3px #CCC; width:680px;> Write the mail body here... </div"

        // Add FROM and TO address, along with SUBJECT and BODY.
        string sFromAdress = "arun@gmail.com";      // From address.
        string sToAddress = "xyz@gmail.com";        // To address.

        System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(
                sFromAdress, sToAddress, sSubject, sBody);

        mail.IsBodyHtml = true; // Set "true", if the BODY of the email is in HTML format. This is optional.

        // The "SmtpClient() class" and its properties.
        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        client.Host = "smpt.gmail.com";   // SMTP server. You can also use Hotmail smtp server. See this example.
        client.Port = 587;         // You may also post "25".
        client.Credentials = new System.Net.NetworkCredential("arun@gmail.com", "your gmail password");
        client.UseDefaultCredentials = false;
        client.DeliveryMethod =  System.Net.Mail.SmtpDeliveryMethod.Network;

        client.Send(mail);          // Finally, send the email.
    }
}
Vb.Net
Option Explicit On

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub SendEmail(ByVal sender As Object, ByVal e As EventArgs)

        Dim sSubject = "Welcome to encodedna.com"           ' The subject line.
        Dim sBody As String = "Hi, this is a test message from encodedna.com."      ' Email body.

        ' Add FROM and TO address, along with SUBJECT and BODY.

        Dim sFromAddress As String = "arun@gmail.com"
        Dim sToAddress As String = "xyz@gmail.com"
        
        Dim mail As New  _
            System.Net.Mail.MailMessage(sFromAddress, _
                                        sToAddress, sSubject, sBody)
        
        mail.IsBodyHtml = True      ' Set "True", if the BODY of the email is in HTML format. This is optional.

        ' We will now use the "SmtpClient()" class and its properties.
        Dim client As New System.Net.Mail.SmtpClient()
        client.Credentials = New System.Net.NetworkCredential("arun@gmail.com", "your gmail password")
        client.Host = "smtp.gmail.com"      'The smtp server.
        client.Port = 587
        client.UseDefaultCredentials = False
        client.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.Network

        client.Send(mail)      ' Finally, send the email.
    End Sub
End Class

An Overview of the above code

If you are using a function in your application repeatedly, then it’s a good practice to write the function in a Class, so you can use the function from different modules, repeatedly. However, in the above example Iam calling the sendMail procedure with the click of a button.

The built-in Class MailMessage() of namespace System.Net.Mail will hold the "from address", "to address", the "subject" and the "body" of the e-mail.

Dim mail As New System.Net.Mail.MailMessage(sFromAdress, sToAddress, sSubject, sMatter);

Finally, we will use the SmtpClient() class and its properties to send an email by assigning a specific SMTP server.

Dim client As New System.Net.Mail.SmtpClient();

client.Host will have the SMTP server of your choice, such as smtp.gmail.com or the server alloted for your website.

Testing Email using "localhost"

Before sending emails from a server, it is good to test your email structure like, its contents etc. using localhost. To do this, you need to configure the "web.config" file to tell .Net that your Email delivery method is local (for the time being) and you need to define a temporary "location" where your mail will be delivered (the folder and path).

web.config

Open the "web.config" file in your project and set the location like this.

<system.net>
    <mailSettings>
        <smtp deliveryMethod="SpecifiedPickupDirectory">
	        <specifiedPickupDirectory pickupDirectoryLocation="C:\EmailTest"/>
        </smtp>
    </mailSettings>
</system.net>

I have the delivery method and "defined a path", where it will drop the mails.

Now, update the delivery method code in the code behind procedure.

client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.Send(mail);          // Finally, send the email.

Ports to Send Email

Some of the popular ports that we often use to send e-mails are 587 and 25. In this demo, I am using port 587.

Ref: Learn more about SMTP and its ports

Hope this article will help you understand the basics of sending emails using Asp.Net in-built classes, methods and properties. Before testing it using an STMP server, please check if you have the necessary permissions. You might also have to temporarily disable the windows (or anti virus) firewall.

Happy coding. 🙂

Next →