Sending an e-mail with ASP.NET and System.Net.Mail via Google

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;
       }
   }
}

Comments

Leave a Reply

You may use simple HTML to add links or lists to your comment. Also use <pre><code class="language-*">...</code></pre> to mark up code snippets. We support language-js, language-markup and language-css for comments.
(Optional)