Thursday, December 25, 2008

How to create contact forms for your websites

Let's start with something simple. You want to create a contact form for your users but having trouble with your hosting provider, because they either charge you or just having problems using their SMTP clients. No worries, Google provides free SMTP service, because they are simply a caring and giving community to all of their users worldwide. No that's not true, they literally are making money of you because you're reading your mails. But you can't blame them because they are providing better service than others can you? You write a leaner and user friendlier search engine or e-mail account and you will make money on the rest of the world too.

Back to our case, if you want your users to send mails throughout your site without publishing your e-mail address you will have to use these following classes:

MailMessage
MailAddress
SmtpClient
NameValueCollection
NetworkCredential

Let's say your form is as following:

When the submit button is clicked we will have to use a SMTP client to send our mail.
Following code should do the trick:


MailMessage msg = new MailMessage();
msg.From=new MailAddress(TextBox5.Text,"");
msg.To.Add("yourAddress@gmail.com");
msg.IsBodyHtml = true;
msg.Subject = ("My contact form");
msg.Body = (TextBox1.Text + TextBox2.Text + " @ "+ TextBox5.Text + " has submitted the following information:
" + TextBox3.Text +"
"+ TextBox4.Text+"
"+ TextBox5.Text+ "
Regarding: "+ DropDownList1.SelectedItem+"
"+ CheckBoxList1.SelectedItem.Text);


SmtpClient sc = new SmtpClient("smtp.gmail.com", 587);
NameValueCollection col = new NameValueCollection();
col.Add("info", "inf");
msg.Headers.Add(col);

sc.Credentials = new System.Net.NetworkCredential("yourAddress@gmail.com", "yourPassword");
sc.EnableSsl = true;

sc.Send(msg);



Here you go, you've got a mail from your user. Gmail uses ports 465 and 587 for SMTP access. You should adjust your mail body according to your needs.

No comments:

Post a Comment