Send Emails in Asp.Net using SmtpClient() - How to Send Email in Asp.Net - C# and Vb.Net

The SmtpClient() class in .Net, provides necessary functions to send e-mails across the web. It is one of most popular means of sending e-mails in Asp.Net. It uses SMTP (Simple Mail Transfer Protocol). Here, in this article I am going to show you how to send Emails in Asp.Net (smpt.gmail.com). This article is for beginners and has codes for C# and VB developers.

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

Related: Sending emails in Asp.Net C# using Hotmail SMTP Mail Server

The Markup

The page is simple and all I have on the 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 style="width:300px;font:13px Verdana;">
            
            <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 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.
        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";
        client.Port = 587;
        client.UseDefaultCredentials = false;
        client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis;

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

Related: Sending 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"
        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 pages, repeatedly. However, in the above example I am calling the SendMail procedure with the click of a button.

The in-built Class MailMessage() of namespace System.Net.Mail will hold the from address, to address, the subject of the e-mail 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 basic of sending emails using Asp.Net in-built classes, methods and properties. Before testing it using an STMP server, please check you have necessary permissions.

If you have any other query regarding this article, please do not hesitate ask. Simply leave your message/query below.

Thanks for reading.

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+
comments powered by Disqus

Join our Google Plus Community and be a part of a discussion!