Sending mail with ASP.NET and Gmail

After a server upgrade I had to setup my mail again. It seems that IIS7 has lost it’s core mail functionality, so I tried to use the SMTP service from Gmail for sending my e-mail. First thing I did is to setup a simple test page, that I would like to share with you.


The page contains a simple web form for inserting some test data and is looking like this:




The markup code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="gmail_mailtest.aspx.cs" Inherits="SendMail" %>
<head runat="server"><title>Email Test Page</title></head>
    <form id="form1" runat="server">
        Message to: <asp:TextBox ID="txtTo" runat="server" Text="[your_mail]" /><br>
        Message from: <asp:TextBox ID="txtFrom" runat="server" Text="[yourname]" /><br>
        Subject: <asp:TextBox ID="txtSubject" runat="server" Text="test from mailtest.aspx" /><br>
        Message Body:<br>
        <asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine" Width="270px" Text="test123" /><br>
        <asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email via Gmail" /><br>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Code behind

The code behind is handling the connection to Gmail:

using System;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
    protected void Btn_SendMail_Click(object sender, EventArgs e)
        MailMessage mailObj = new MailMessage(
            txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Host = "";
        smtpClient.Port = 587;
        smtpClient.Credentials = new System.Net.NetworkCredential("[yourname, without the]","[PaSSWoRD]");
        smtpClient.EnableSsl = true;

           Label1.Text = "Mail is sent!";
            catch (Exception ex)
            Label1.Text = ex.ToString();
Tadaa, it works like a charm!