Send that email through GMail from C#

Often we’ll need to send out email from websites containing notifications etc. Traditionally I installed the MS mail service (an open relay mail server) on the server and cracked on. That probably isn’t best practice and its difficult to give the client access to sent mail, so I started using GMail. I realise this may not always be possible but I find it really handy.

Setup is super simple. First update your web.config (saves configuring those objects in code…)

<system.net>
    <mailSettings>
      <smtp from="from@address.com" deliveryMethod="Network">
        <network host="smtp.gmail.com" port="587" userName="" enableSsl="true" password="">
      </smtp>
    </mailSettings>
</system.net>

Sending mail from code is now really easy….

var message = new MailMessage();
message.IsBodyHtml = true;
message.Subject = "{subject}";
message.To.Add("{receipient email address}");
message.Body = "{funky mail body}";

var client = new SmtpClient();
client.Send(message);