Pages

Friday, November 11, 2011

Sending Email In ASP.NET 2.0


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.NET - Imports 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.NET - public MailMessage (String From, String toString 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="somesmtpserverport="25userName="namepassword="passdefaultCredentials="true" />
      </smtp>
    </mailSettings>
 </system.net>
 
References :
 
Conclusion:
 
In this short article, we explored how easy it is to send Email’s with attachments using the classes in System.Net.Mail. This approach of sending mails will remain the same for web as well as windows application.

No comments:

Post a Comment