Sending email through Gmail SMTP server - C# and Powershell examples

13. January 2013 23:38 by Jay Grossman in   //  Tags: , , , , ,   //   Comments (0)

I know I haven't posted much code on this blog, but this snippet I found valuable.

While I can certainly host my SMTP server, it would be so much easier if I could just Google's (since I am using Google Apps for my site's email). Below is the code you can use to send email's via Google's SMTP server. enjoy...



string GmailUserName="";

string GmailPassword="mypassword";

string SendTo="";

string EmailSubject="Test Subject";

string EmailBody="Test Body";


System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("", 587);

client.Credentials = new NetworkCredential(GmailUserName, GmailPassword);

client.EnableSsl = true;

client.Send(GmailUserName, SendTo, EmailSubject, EmailBody);






$emailFrom="myusername <>"


$emailMessage=New-Object System.Net.Mail.MailMessage$emailFrom , $emailTo )

$emailMessage.Subject="Test Subject"



<p>Here is a message that is <strong>HTML formatted</strong>.</p>

<p>From the SMTP script</p>


$SMTPClient=New-Object System.Net.Mail.SmtpClient$emailSmtpServer , $emailSmtpServerPort )


$SMTPClient.Credentials=New-Object System.Net.NetworkCredential$emailSmtpUser , $emailSmtpPass );

$SMTPClient.Send$emailMessage )


After this code sends the email, it will appear in the account's Gmail sent mail folder (just as if you had sent it via tthe site).

Since Gmail does not have much of a mail merge option unless you use Google Docs, I wound up using this code for personalizing messages within an opt-in email newsletter.

About the author

Jay Grossman

techie / entrepreneur that enjoys:
 1) my kids + awesome wife
 2) building software projects/products
 3) digging for gold in data sets
 4) my various day jobs
 5) rooting for my Boston sports teams:
    New England PatriotsBoston Red SoxBoston CelticsBoston Bruins

Month List