Using Gmail SMTP server in ASP.Net

If you are doing some development where your code needs to send emails, and you don’t have SMTP server set up, you can use Gmail’s own SMTP.

You’ll need to have Gmail user account to be able to do this, as all emails that you send will be sent from your user account. Also, if you have 2 step verification enabled for your Google account, you will need to set up new application specific password to use in your code. For more details on how to do this, see Google’s support page.

First, create application settings keys in your web.config file to store SMTP and email related configuration (this will make it easier when moving site between environments where you might use different SMTP servers).

     <add key="SMTPServer" value=""/>
     <add key="SMTPServerPort" value="587"/>
     <add key="SMTPUser" value=""/>
     <add key="SMTPpwd" value="GmailOrAppSpecificPwd"/>
     <add key="ContactEmail" value="EmailAddressToSendTo"/>

Then use the code as follows:

string toEmail =
string mailServer =
string mailServerPort =
string subject =
     "My Email Subject";
string fromEmail =
     fromEmailAddress; //e.g. address user has entered on contact us web page
string body =
     "Email message";
MailMessage contactEmail =
     new MailMessage(fromEmail, toEmail, subject, body);
SmtpClient smtpClient =
     new SmtpClient(mailServer, int.Parse(mailServerPort));
System.Net.NetworkCredential SMTPUserInfo = new
smtpClient.Credentials = SMTPUserInfo;
smtpClient.EnableSsl = true;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s