Tuesday, March 24, 2009

Sending a mail through SMTP

SMTP(Simple Mail Trafer Protocol) is an application layer protocol. It is a internet's standard host-to-host mail transport protocol and traditionally operates over TCP,port 25.It uses TCP as a transport protocol, and in turn uses IP for routing.

Now lets us look at the code for sending a mail to a user who have just registered-

Code in aspx.cs-
string fromAddress = ConfigurationManager.AppSettings["FromAddress"];
string data = "Your UserName=" + txtEMail.Text + "
" + "Your Password= " + txtPassword.Text + "
" +
"Using the following link please validate your registration" + "
" +
"Request.Url.Scheme"+"://"+"Request.Url.Host"+"/Validate.aspx?userName=" + txtEMail.Text + "&userId=" + primaryContact.UserId;

MailMessage mailer = new MailMessage(fromAddress, txtEMail.Text);
mailer.Body = data;
mailer.Subject = WebUtil.GetTranslatedString("EMAIL_SUBJECT");
mailer.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Send(mailer);

Tag to be added in web.config-


system.net
mailSettings
smtp deliveryMethod="Network" from=the mail id of the site
network host="hostname" defaultCredentials="true"/
/smtp
/mailSettings
/system.net
(Please add the pre and post the symbols '<' and '>')

By this code the user will recieve a mail through the site in which they got registered.The mail will appear in the below manner

The mail content-

Your UserName="EmailId of the user" Your Password= "password of the user"

Using the following link please validate your registration :

http//HostName/Website/Default.aspx?username=username&userId=some uniqueidentifier

Note:The total path of the page u want to display for the user once the user logs in,is the link above given to the user in his/her mail.

  • The above link is given to the user to validate his registration.Once the user clicks the link he will be a valid user and will be redirected to the validate page of the website .In that page the user can be given a button for redirecting to the default first page of the site.After this the user can loggin with his credentials using login page of the site.
  • If the user will not click that link provided in his mail he cannot loggin in the website with his account.
  • In this way we can code the mail sending technique usind the SMTP protocol.

No comments: