Tuesday, April 21, 2009

GMail SMTP Setting To Send Email From ASP.net Application

First of all , It is required to configured GMail.

1. Create Gmail account or use existing if you already have it.
2. Log in into Gmail.
3. Go Settings.
4. Go Forwarding and Enable IMAP/POP3
5. In that go to last section and enable IMAP.

Now in your Web Application / Web Site project , open web.config. Add following to web.config.

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

GMail IMap Service runnig at port 587 so you must required to configured that. Also Gmail required SSL authentication so it is required to enable ssl for SMTPClient.

MailMessage message = new MailMessage();
message.From = new MailAddress(
from@gmail.com);
message.To.Add("to@gmail.com");

SmtpClient client = new SmtpClient();        
client.EnableSsl = true;            
client.Send(message);

Yuo can not enable SSL in web.config so you must required to configure it explicitly.

7 comments:

Anonymous said...

Thanks! this is exactly what I was looking for to use gmail as the smtpclient and how to alter an existing asp.net app.

SereniTEA infusions said...

This excellent work explained in simple terms. I have used it sucessfuly. Only thing I could not get the senders email address as I am using gmail to relay the email and so I get my gmail account as sender.

Unknown said...

Great article. I'm beginning to learn .NET and was curious to know if it's bad practice to expose your username and password in your web.config file. Is there a better way of doing things?

Ryan

dotnetstep said...

Hi Ryan,
Most of the time people placed password in web.congif file.As nobody can directly read that file without permission. But if you are using system that can be access by multiple users then you can secure it following way.

1. Encrypt SMTP Section.
http://msdn.microsoft.com/en-us/library/dtkwfdky.aspx
For tihs you have to provide machinekey in web.config.

2. Store username/password in db with encryption.
Set credential property of each class(SmtpClient, HttpWebRequest)at run time.
You can load this data into global varaible at application startup time.

Let me know if you still need more information.

jason palmer said...

thanks, this is fantastic, i ran around and used a microsoft video etc. and had no luck but this worked great

Anonymous said...

i could not figure this problem out ANYWHERE! amazing article!

Anonymous said...

Fantastic article. I couldnt find the answer to this problem ANYWHERE until i found your post! thanks!