Published On: Tue, May 17th, 2011

Sending Email In ASP.NET 2.0

Share This
Tags

In ASP.NET, sending emails has become simpler. The classes required to send an email are contained in the System.Net.Mail. The steps required to send an email from ASP.NET are as follows :
Step 1: Declare the System.Net.Mail namespace
C# – using System.Net.Mail;
VB.NETImports System.Net.Mail
Step 2: Create a MailMessage object. This class contains the actual message you want to send. There are four overloaded constructors provided in this class. We will be using
C# – public MailMessage ( string from, string to, string subject, string body )
VB.NETpublic MailMessage (String From, String to, String subject, String body)
The constructor of this MailMessage class is used to specify the sender email, receiver email, subject, body.
C#
MailMessage message = new MailMessage            (“abc@somedomain.com”,”administrator@anotherdomain.com”,”Testing”,”This is a test mail”);
VB.NET
Dim message As MailMessage = New MailMessage (“abc@somedomain.com”,”administrator@anotherdomain.com”,”Testing”,”This is a test mail”)
Step 3: To add an attachment to the message, use the Attachment class.
C#
string fileAttach = Server.MapPath(“myEmails”) + “\\Mypic.jpg”;
Attachment attach = new Attachment(fileAttach);
message.Attachments.Add(attach);
VB.NET
Dim fileAttach As String = Server.MapPath(“myEmails”) & “\Mypic.jpg”

Dim attach As Attachment = New Attachment(fileAttach) message.Attachments.Add(attach)

Step 4:After creating a message, use the SmtpClient to send the email to the specified SMTP server. I will be using ‘localhost’ as the SMTP server.

C#
SmtpClient client = new SmtpClient(“localhost”);
client.Send(message);
Additionally, if required, you
client.Timeout = 500;
// Pass the credentials if the server requires the client to authenticate before it will send e-mail on the client’s behalf.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
VB.NET
Dim client As SmtpClient = New SmtpClient(“localhost”)

client.Send(message)

Additionally, if required, you client.Timeout = 500

‘ Pass the credentials if the server requires the client to authenticate before it will send e-mail on the client’s behalf.

client.Credentials = CredentialCache.DefaultNetworkCredentials

That’s it. It’s that simple.
To configure SMTP configuration data for ASP.NET, you would add the following tags to your web.config file.
<system.net>
<mailSettings>
<smtp from=”abc@somedomain.com”>
<network host=”somesmtpserver” port=”25″ userName=”name” password=”pass” defaultCredentials=”true” />
</smtp>
</mailSettings>
</system.net>

Leave a comment

XHTML: You can use these html tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>