Web development · 30 Aug 2014 · 1 min read

Configure an ASP.NET website to send emails via SMTP (Gmail)

Every website ends up needing to send email at some point — a contact form submission, a notification, a password reset. Sending mail was awkward in Classic ASP and ASP.NET 1.1, but the ASP.NET 2.0 framework onward made it straightforward.

What you need

  • A website (the one you’re building or maintaining)
  • An SMTP server to send mail through
  • A username and password to authenticate against that server

The code

public static void SendMail(string MailTo, string MailFrom, string Subject, string MailBody)
{
    System.Net.Mail.MailMessage objMailMessage = new System.Net.Mail.MailMessage(MailFrom, MailTo);
    objMailMessage.Subject = Subject;
    objMailMessage.IsBodyHtml = true;
    objMailMessage.ReplyTo = new MailAddress("username@domain.com");
    objMailMessage.Body = MailBody;

    SmtpClient objsmtp = new SmtpClient();
    objsmtp.EnableSsl = true; // required if you're sending through a Gmail or Google Workspace account
    objsmtp.Send(objMailMessage);
}

Call this function with the right arguments wherever you need to send a message, and it handles the rest.

Web.config settings

Add the following to your website’s web.config:

<system.net>
  <mailSettings>
    <smtp from="username@gmail.com">
      <network host="smtp.gmail.com" port="587" password="email-password" userName="username@gmail.com" />
    </smtp>
  </mailSettings>
</system.net>

The default SMTP port is 25, but Gmail and Google Workspace accounts use 587. If neither port works, check with your email provider for the correct one.

Have a tender deadline or a system that needs rescuing?

Tell us the scope. We'll come back within one working day with a plan and a number.

Talk to us

Peak performance
& connectivity

31.10°N 77.17°E — Kasumpti, Shimla — 2,205 m