Sunday, June 15, 2008

Tutorial : Sending E-mail using ASP.net through Gmail account (Gmail SMTP Server account)


ShareThis
Sending Email is a basic task of a web application for many purposes like- Error logging, Reporting, Newsletters, and Performance alerting as well as for many other reasons.

If you have taken web space somewhere on a web server then you are provided with the Email accounts and SMTP and POP services for sending and receiving E-mails. Some times you don't have SMTP server accounts and you may want to send email. Or Sometimes, for other reasons also you may want to use third-party SMTP sever for sending E-mails .

Gmail is a good solution for this purpose. Gmail provides SMTP and POP access which can be utilized for sending and receiving E-mails.
Here in this tutorial we will be using a Gmail account for sending email by SMTP.

Note:
1. Gmail has a fixed number of quota for sending emails per day, means you may not be able to send unlimited number of e-mails using Gmail due to anti-spamming restrictions.

2. You may not be able to send same e-mail to unlimited number of people, because Gmail's anti-spamming engine restricts for this too.

So, Gmail can be used for sending limited number of e-mails daily to select people only. If you still need to send numerous e-mails to numerous people you can register for a Google Group account and can use that e-mail address to send email to registered members of that group. I will come up with that tutorial in near future.

Requirements:
1. An active Gmail account is required to test this application.
2. Visual Studio 2005

Here we go:

Step 1:
Create a new web application in visual studio and add a Web form to it.
Next add a Button to the form and double click this button to bring the code for click event of this button in the code window. Copy paste the following code to the click event.

Note: Don't forget to replace the To and From fields as well as the correct password for successfully sending the mail.
------------------------------------------------------------------------------------------

string from = me@gmail.com; //Replace this with your own correct Gmail Address

string to = you@gmail.com //Replace this with the Email Address to whom you want to send the mail

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

mail.To.Add(to);

mail.From = new MailAddress(from, "One Ghost" , System.Text.Encoding.UTF8);

mail.Subject = "This is a test mail" ;

mail.SubjectEncoding = System.Text.Encoding.UTF8;

mail.Body = "This is Email Body Text";

mail.BodyEncoding = System.Text.Encoding.UTF8;

mail.IsBodyHtml = true ;

mail.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();

//Add the Creddentials- use your own email id and password

client.Credentials = new System.Net.NetworkCredential(from, "Password");

client.Port = 587; // Gmail works on this port

client.Host = "smtp.gmail.com";

client.EnableSsl = true; //Gmail works on Server Secured Layer

try

{

client.Send(mail);

}

catch (Exception ex)

{

Exception ex2 = ex;

string errorMessage = string.Empty;

while (ex2 != null)

{

errorMessage += ex2.ToString();

ex2 = ex2.InnerException;

}

HttpContext.Current.Response.Write(errorMessage );

} // end try

------------------------------------------------------------

Note: Don't forget to replace the To and From fields as well as the correct password for successfully sending the mail.

Step 2: Run the web application and click on the Button to send the mail. Check the E-mail whether you get the mail successfully or not.

Some-times it takes 2-3 minutes or more to reach the mail to the destination server. So check after a while, if you do not get it soon.

-------------------------
Get back to me if you are not able to execute the application. I will be happy to help you out.



20 comments:

Amit said...

//Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "Password");


in this fild i was make aror
so please make sure exampal to me

including email

my mail id is "amitb.pd@gmail.com"
please send me this all line

xiaoyi said...

I seems to me that you can only send an email to gmail email not other ones when using gmail SMTP server in ASP.net.
Please confirm that.

sabuj said...

hi i face problem.the error message is "The remote name could not be resolved: 'smtp.gmail.com'"
how can i solve please help me...

Sumit Pranav said...

Hi xiaoyi !
Yuu are wrong you can send Email from Gmail using this sript to any Email.

Sumit Pranav said...

Hi xiaoyi !

You getting this error :
"The remote name could not be resolved: 'smtp.gmail.com'"

I think its temporary DNS error. otherwise smtp.gmail.com is testing for sending mail as smtp server.

Send me ur complete code So that I can help you out.

lakshmi said...

hi,
i am getting error in these lines as ;expected
string from = lakshmisudha.yakkala@gmail.com;
string to = sudha1917@gmail.com;

Sumit Pranav said...

Hi! lakshmi!
Pls share your code so that I can help you further.
Send on-
spscreen-pub@yahoo.co.in

lakshmi said...
This comment has been removed by the author.
Sumit Pranav said...

@Lakshmi
I think you are not providing the correct credentials to login.
Pls ensure you have put correct Gmail User ID and Password

lakshmi said...

hi pranav,
its working now.u r project was really nice.thanks alot

lakshmi said...
This comment has been removed by the author.
Fatma Zayed said...

i have that error

System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: The remote name could not be resolved: 'smtp.gmail.com' at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) --- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.Send(MailMessage message) at _Default.Button1_Click(Object sender, EventArgs e) in c:\Users\Administrator\Desktop\Sending Mail\Default.aspx.cs:line 47System.Net.WebException: The remote name could not be resolved: 'smtp.gmail.com' at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message)

Fatma Zayed said...

this new error
Failure sending mail.
so why that

Anonymous said...

Hi i m getting the same error as Fatma Zayed is getting so kindly tell the solution for that..

Prince said...

Hie sumit, i am getting an error which says Failure Sending Email.

swathi said...

When i use this code for the first time i received the mail but later on i cant able to receive the mail but i can able to see the sent mail list in sending email account so please let me know y it is not able to sent the mail and i'm not getting any errors.

ahilan said...

System.Net.Mail.SmtpException: Command not implemented. The server response was: 5.5.1 Unrecognized command. e3sm18793963pbi.7 at System.Net.Mail.StartTlsCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.StartTlsCommand.Send(SmtpConnection conn) at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) at _Default.Button1_Click(Object sender, EventArgs e) in c:\Users\Dinesh\Documents\WebSite5\Default.aspx.cs:line 49

phoon said...

May I have a VB code of this? I have no idea how to convert it to vb code.

Pooja said...

i have error

System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 173.194.77.108:25 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) --- End of inner exception stack trace --- at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) --- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.Send(MailMessage message) at Default3.Button1_Click(Object sender, EventArgs e)System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 173.194.77.108:25 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) --- End of inner exception stack trace --- at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message)System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 173.194.77.108:25 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)


plz help me to resolve it.
thanks

Sumit Pranav said...

@Pooja

Are you using a valid SMTP server and its credentials.
Check port number and alsof if your server allows connections from outside.

Send me your code for any help.