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).

<appSettings>
     <add key="SMTPServer" value="smtp.gmail.com"/>
     <add key="SMTPServerPort" value="587"/>
     <add key="SMTPUser" value="YourEmail@gmail.com"/>
     <add key="SMTPpwd" value="GmailOrAppSpecificPwd"/>
     <add key="ContactEmail" value="EmailAddressToSendTo"/>
</appSettings>

Then use the code as follows:

string toEmail =
     ConfigurationManager.AppSettings["ContactEmail"].ToString();
string mailServer =
     ConfigurationManager.AppSettings["SMTPServer"].ToString();
string mailServerPort =
     ConfigurationManager.AppSettings["SMTPServerPort"].ToString();
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
     System.Net.NetworkCredential(
          ConfigurationManager.AppSettings["SMTPUser"].ToString(),
          ConfigurationManager.AppSettings["SMTPpwd"].ToString()
     );
smtpClient.Credentials = SMTPUserInfo;
smtpClient.EnableSsl = true;
smtpClient.Send(contactEmail);
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s