Few days ago I needed to develop contact form handler for the website hosted on Windows platform. JavaScript and AJAX were used on the client side to send request to the server. After some reading about ASP.NET framework it become clear that I need to write custom handler (.ashx) to process this request.
In the example below Google is used as e-mail service provider. If you have Google Apps account replace username@gmail.com with your e-mail address including domain name.
send_inquiry.ashx:
<%@ WebHandler Language="C#" class="ContactFormHandler" %>
using System;
using System.Web;
using System.Net.Mail;
public class ContactFormHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587; // or 465
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("username@gmail.com", "password");
MailMessage msg = new MailMessage();
msg.From = new MailAddress("username@gmail.com");
msg.To.Add("To@address.com");
msg.Subject = "Web site inquiry";
// Additional options
// msg.IsBodyHtml = true;
// msg.BodyEncoding = Encoding.UTF8;
// msg.Priority = MailPriority.High;
string strName = context.Request.Form["name"];
string strEmail = context.Request.Form["email"];
string strPhone = context.Request.Form["phone"];
string strMessage = context.Request.Form["message"];
string strBody = "";
strBody += "Name: " + strName + "\n";
strBody += "E-mail: " + strEmail + "\n";
strBody += "Phone: " + strPhone + "\n";
strBody += "Message:\n" + strMessage + "\n";
msg.Body = strBody;
context.Response.ContentType = "text/plain";
try {
smtp.Send(msg);
context.Response.Write("Success");
} catch (Exception e) {
context.Response.Write("Failure (" + e.ToString() + ")"); ;
}
msg.Dispose();
}
public bool IsReusable {
get {
return false;
}
}
}
