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.

Must Read: How to Send Emails in Asp.Net C# using Hotmail SMTP Mail Server

The Markup

The page is very simple. All I have in my web page are two controls, an Input box and a button control. I want my users to enter the email id in the input box and click the button to send the email. The button’s onserverclick event will call a procedure written at the code behind section of this application.

<!DOCTYPE html>
<html>
<head>
    <title>Send Email in Asp.Net</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <label>
                Enter Email ID
                    </label>
            
            <input type="text" id="emailid" runat="server" /> <br />
           
            <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.

        // THE BODY OF THE E-MAIL.
        string sBody = "Body of the e-mail.";

        // You can design the body section of you mail by adding markup.
        // for example: 
        // sBody = "<div style=border:solid 3px #CCC; width:680px;> Write the mail body here... </div"

        // ADD "FROM" AND "TO" ADDRESS, ALONG WITH THE SUJECT AND BODY.
        System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(
            "webmaster@yourwebsite.com", "xyz@gmail.com", sSubject, sBody);

        // SET "True" IF THE BODY OF THE MAIL IS IN HTML FORMAT.
        mail.IsBodyHtml = true;

        // The "SmtpClient() class" and its properties.
        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        client.Host = "smtp.examplesmtpserver.com";   // SMTP server. You can also use smpt.gmail.com
        client.Port = 587;
        client.UseDefaultCredentials = false;
        client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis;

        client.Send(mail);          // FINALLY, SEND THE MAIL.
    }
}

You might also like: How to Send Emails in Asp.Net C# using Hotmail SMTP Mail Server

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.

        ' THE BODY OF THE E-MAIL.
        Dim sBody As String = "Hi, this is a test message from encodedna.com."

        ' YOU CAN DESIGN THE BODY SECTION OF YOUR MAIL BY ADDING A LITTLE MARKUP. 
        ' FOR EXAMPLE: 
        'sBody = "<div style=border:solid 3px #CCC; width:680px;> WRITE YOU BODY HERE... </div"

        ' ADD "FROM" AND "TO" ADDRESS, ALONG WITH THE SUJECT AND BODY.
        Dim mail As New  _
            System.Net.Mail.MailMessage("webmaster@yourwebsite.com", _
                                        "xyz@gmail.com", sSubject, sBody)

        ' SET "True" IF THE BODY OF THE MAIL IS IN HTML FORMAT.
        mail.IsBodyHtml = True

        ' WE WILL NOW USE THE "SmtpClient() CLASS" AND ITS PROPERTIES.
        Dim client As New System.Net.Mail.SmtpClient()
        client.Host = "smtp.examplesmtpserver.com"      ' SOME SMTP SERVER. FOR EXAMPLE smpt.gmail.com
        client.Port = 587
        client.UseDefaultCredentials = False
        client.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis

        client.Send(mail)               ' FINALLY, SEND THE MAIL.
    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 I am 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("webmaster@yourwebsite.com", “xyz@gmail.com”, 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 the email structure, its contents and everything using “localhost”, that is, on your machine. To do this, you need to configure the “web.config” file and 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

<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 part in the code behind procedure SendMail.

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

Note: Don't forget to remove or comment this line once you are done testing on localhost and add the orginial method, that is, “PickupDirectoryFromIis”.

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

client.DeliveryMethod will handle delivery of the e-mail using the PickupDirectoryFromIis, which means the e-mails will be delivered from the IIS directory of the server you are using for hosting your website.

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.

Thanks for reading.

Next →