Sending Email From Your Web Site
Writing code that send e-mail from an ASP.Net page is pretty straightforward.
Inside the System.Net.Mail namespace you find
the number of classes that make it easy to send email message.
These classes enable you to create message,
add subject, add address etc.
following figure describe four classes that typically use when sending E-Mail :
Lets do some practical..
Figure 1.1
1. Start by adding a new text file to App_Data Folder in your web application.If
you don't have App_Data Folder, Right click root directory add Asp.net folder---App_Data.
Give name to text file as ContactForm.txt.
2. Enter the following text in the text file, include place holder...
Hi there,
A User has left the following feedback at site:
Name: ##Name##
E-mail address: ##Email##
MobileNo: ##MobNo##
Comments: ##Comments##
Save and close the file.
3. add Contactform.aspx page to your Application and design the page as shown in
figure 1.1.
4. Open the code behind of contactForm.aspx and add the following name space.
using System.Net.Mail;
using System.IO;
Note
System.Io provide access to the file
class
5. On click event of Send Button write down the following code
protected
void nSend_Click(object
sender, EventArgs e)
{
string filename = Server.MapPath("~/App_Data/ContactForm.txt");
string mailbody = File.ReadAllText(filename);
mailbody =
mailbody.Replace("##Name##",TxtName.Text);
mailbody =
mailbody.Replace("##Email##", TxtEmail.Text);
mailbody =
mailbody.Replace(" ##MobNo##", TxtMob.Text);
mailbody =
mailbody.Replace("##Comments##",
TxtComment.Text);
MailMessage mymsg =
new MailMessage();
mymsg.Subject =
"Response from web...";
mymsg.Body = mailbody;
mymsg.Priority =
MailPriority.High;
mymsg.From =
new MailAddress("[email protected]",
"WebFeedback");
mymsg.To.Add(new
MailAddress("[email protected]",
"Admin"));
SmtpClient client =
new SmtpClient();
client.Host =
"smtp.gmail.com";
client.Port = 587;
client.EnableSsl =
true;
client.UseDefaultCredentials = false;
client.Credentials =
new System.Net.NetworkCredential("[email protected]",
"PA$$$$$$$");//Ur
emailid and password
client.DeliveryMethod =
SmtpDeliveryMethod.Network;
client.Send(mymsg);
Label1.Text =
"Email send";
}
6. Save all your changes and press ctrl+f5.
7. Check your email account. you should receive an email.
Figure 1.2