Send Emails in ASP.NET 2.0 with Authentication


Sending emails from ASP.NET 2.0 application is made very simply using MailMessage and SmtpClient classes available in System.Net.Mail namespace in .NET Framework. Sometimes SMTP server required authentication information of email client to send emails. In the following tutorial, I will show you how you can authenticate smtp client when sending emails in ASP.NET 2.0.

You need to import System.Net.Mail and System.Net namespaces to test following code.

C#

string mailFrom = "FromEmailAddressHere";
string mailTo = "ToEmailAddressHere";

string subject = "ASP.NET Test Email";

string messageBody = "This email is send to you from ASP.NET";

// Create Mail Message Object
MailMessage message = new MailMessage(mailFrom, mailTo, subject, messageBody);

// Create SmtpClient class to Send Message
SmtpClient client = new SmtpClient();

// Here you specify your smtp host address such as smtp.myserver.com
client.Host = "localhost";

// Specify that you dont want to use default credentials
client.UseDefaultCredentials = false;

// Create user credentials by using NetworkCredential class 

NetworkCredential credential = new NetworkCredential();
credential.UserName = "waqas";
credential.Password = "secret";
client.Credentials = credential;
client.Send(message);

VB.NET

Dim mailFrom As String = "FromEmailAddressHere"
Dim mailTo As String = "ToEmailAddressHere"
Dim subject As String = "ASP.NET Test Email" 
Dim messageBody As String = "This email is send to you from ASP.NET"

' Create Mail Message Object 
Dim message As New MailMessage(mailFrom, mailTo, subject, messageBody)

' Create SmtpClient class to Send Message 
Dim client As New SmtpClient()

' Here you specify your smtp host address such as smtp.myserver.com 
client.Host = "localhost"

' Specify that you dont want to use default credentials 
client.UseDefaultCredentials = False

' Create user credentials by using NetworkCredential class 

Dim credential As New NetworkCredential() 
credential.UserName = "waqas" 
credential.Password = "secret" 
client.Credentials = credential

client.Send(message)​

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments