Send Email Using Gmail Or SMTP ASP.NET C# VB.NET

If you want to send email using your Gmail account or using Gmail's smtp server in ASP.NET application or if you don't have a working smtp server to send mails using your ASP.NET application or aspx page than sending e-mail using Gmail is best option.

you need to write code like this

First of all add below mentioned namespace in code behind of aspx page from which you want to send the mail.

using System.Net.Mail;

Now write this code in click event of button

Continue reading here


If you like this post than join us or share

54 comments:

Thảo Khơi said...

Very good, thank you for your coding!
I think i can learn more from this, i am an IT student in Vietnam. I would like to ask you any thing about software development, can you help me?
-----------
Good day!


Unknown said...

hey tht was awesone


Adeeb said...

Thnxs

It is working fine

keep on :)


Unknown said...

thanks for your code
dlfree.net


Anonymous said...

I am making a project on online examination. for login page, i want that first username given is searched in database; if it is not available then display message"user not valid", else retrive corresponding password from database and match it with password provided and validate it.
can you please send me code for this in Asp. Net, C# or AJAX.
Please send me solution at amitkj.2989@gmail.com


Anonymous said...

Hi,

I just tried it; it didn't give any error neither did it do anything.

What could be the problem?

Emmao.


Anonymous said...

@:Emmao

Hi Emmao, did you changed mail address in to field ?
MailMessage mail = new MailMessage();
mail.To.Add("jainamit.agra@gmail.com");


Anonymous said...

Hi,
I tried the code but is giving an error:-
"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 209.85.147.109:25"
thanks in advance


Unknown said...

@Anonymous:

The error you are referencing is error from Server's of google , it's not related to code

Check your internet connection, and check the username and password of gmail account you are using to send mail

Hope this solves your problem , do let me know if you face any other problem


Elumalai k said...

I am making a project on online examination. for login page, i want that first username given is searched in database; if it is not available then display message"user not valid", else retrive corresponding password from database and match it with password provided and validate it.
can you please send me code for this in Asp. Net, C# or AJAX.my mail id is elusevenstar@gmail.com


Unknown said...

@Elumalai k : you can do it in two ways , 1. use asp.net membership provider 2. use your own table to check username and password

for second option create a table for storing username and password and then write code in Click event of Login Button like this

private void btnLogin_Click(object sender, EventArgs e)
{
if (txtLogin.Text == "")
{
lblMessage.Text = "User Name cannot be blank";
}
if (txtPwd.Text == "")
{ lblMessage.Text = "Passoword cannot be blank"; }
if (txtLogin.Text != "" && txtPwd.Text.Trim()!= "")
{
CheckLogin();
}

}

private void CheckLogin()
{
string strLogin = txtLogin.Text.Trim();
string strPwd = txtPwd.Text.Trim();
try
{
string[] tables = null;
DataSet objDs = new DataSet();
string strQuery = "Select * From [password]" +
" Where user='" + strLogin.Trim().ToString().Replace("'", "''") +
"'" + " And Pass='" + strPwd.ToString().Replace("'", "''") + "'";

objDs.Fill(strConnString, CommandType.Text, strQuery, objDs, tables);
if (objDs.Tables[0].Rows.Count>0 )
{
Response.Redirect("Default.aspx");

}
else
{
lblMessage.Text = "Incorrect Login information!!!";
}

}
catch (Exception ex)
{
throw new Exception("The method or operation is not implemented.");
}

}


Himanshu said...

i got this error when i run above code(The remote certificate is invalid according to the validation procedure.)in last line
smpt.send(mail)

mr.amit plz reply me at himanshu.kaushik04@gmail.com
waiting for ur reply


Unknown said...

@himanshu:

Remote certificate invalid error suggests your system date might be wrong

Check your system's date and set it to current date and year , check your gmail account username and password and try the code again

Do let me know if you still face the problem


Himanshu said...

hello, amit thanks its working now
but can u give me the code of simple mailing in asp.net with c# not with gmail
in simple emailing i m getting the error

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for himanshu@saibaba.com

waiting for ur reply


thank u so much


Unknown said...

@himanshu:

For sending mail without using gmail, you need to have your smtp server configured on your system

Check your smtp server and pop server settings


Anonymous said...

Hi,

when i'm running your code in the server at godaddy i get this error message: "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 209.85.199.111:25"

But when running at my computer is works ok.

Have any idea what the problem is?

Best regards,
Miguel


Himanshu said...

hi amit,now i can send email in asp.net but cant receive. coz i dont hv coding for this can send me plz how to receive the mails.

can u send me receviing coding

thanks u r the best


Unknown said...

@Miguel:

This is probally issue of your hosting provider , u can ask them


Ankit said...

HI i tried your code it is working on a normal net connection but on a proxy server sending fails

can u tell me what extra things to add so that we can send mails on a proxy server

thanks!!


Unknown said...

@Ankit:

Add this in your application's web.config file.


<system.net>
<defaultProxy>
<proxy proxyaddress="YourProxyIpAddress"/>
</defaultProxy>
</system.net>


And change this line of code in code behind

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

to

smtp.Host = "smtp.gmail.com,587";

do let me know whether it fixes your issue or not ?


Ankit said...

Thanks for the reply,
i added the proxy address in web.config file and added smtp.port=587
but problem still continues :(


Unknown said...

@ankit:

Check whether port 587 is open on your system or not ? it might be blocked by your sys admin or by any firewall

try this code

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = False;
smtp.Credentials = new System.Net.NetworkCredential
("YourUserName@gmail.com","YourGmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);

let me know the exact error you are getting


Anonymous said...

this works well with any smtp server but not with gmail


Anonymous said...

sorry I commented anonimously earlier, your most recent settings do work, thanks


kit said...

thx alot, amiT jaiN !!! =D
btw.....can u teach me how to get the server status?
im a fresh grad from m'sia....asigned to create a program to auto generate an email when the server is down....
i got no idea where to start......

i look forward to hearing from you.THANKSSSS...
yajie_2248@hotmail.com


Unknown said...

Thanks amit. That's very useful tips. Afterall, I would like to express one thing: what is the difference in magnitude in using my own smtp sever and going for my google account? Could I use google account for my production environment also [I don't think so, however]?. Thank you.


Unknown said...

@Sangam:

U can use either smtp or gmail , the difference is , in case u don't have smtp server configured or up and running, or somehow ur smtp server is down than u can use gmail


Wonderkid said...

This comment has been removed by a blog administrator.


Unknown said...

Dim mail As MailMessage = New MailMessage()
mail.To.Add("abcd@gmail.com")
mail.To.Add("abc@hotmail.com")
mail.From = New MailAddress("abcd@gmail.com")
mail.Subject = "Email using Gmail"
Dim body As String = "Hi, this mail is to test sending mail"
mail.Body = body
mail.IsBodyHtml = True
Dim smtp As SmtpClient = New SmtpClient()
smtp.Host = ("150.123.123.132")
smtp.Port = 25
smtp.Credentials = New System.Net.NetworkCredential("150.123.123.132\administrator", "12345")
smtp.EnableSsl = True
smtp.Send(mail)
Getting Error "Failure sending mail."

Any Suggestion?
Thank you
ASAM


Unknown said...

@Atif:

You need to use your gmail email id and password in below mentioned line of code

System.Net.NetworkCredential("150.123.123.132\administrator", "12345")

System.Net.NetworkCredential("yourmailid", "yourpassword")


kris of philippines said...

@amiT jaiN
good day. how can i attach documents in my email, using the code you've provided?


Anonymous said...

I am unable to use. Getting error :

Mail Sending failed.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


Unknown said...

@Above : this seems a problem with your internet connection , u can try the the with ssl enabled and changing port to 587, also make sure u have enabled pop mail forwarding in your gmail account settings


Anonymous said...

can u plz check the following code i am trying it but unable to send mail, its not giving any error
protected void btnSendmail_Click(object sender, EventArgs e)
{
MailMessage message = new MailMessage();

try
{
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);


message.To.Add("basit_systemist@live.com");
message.Subject = "Feedback";

message.From = fromAddress;
message.CC.Add("king_basit@hotmail.com");


message.IsBodyHtml = false;

message.Body = txtMessage.Text;

SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.Credentials = new NetworkCredential("syedbasitalishah@gmail.com", "roseandjasmine");

smtp.Send(message);

lblStatus.Text = "Email successfully sent.";
}
catch (Exception ex)
{
lblStatus.Text = "Send Email Failed.
" + ex.Message;
}
}
}


r4 dsi said...

Sending mail through any of the mail server needs only 3 values.
1)SMTP server name
2)Port
3)SSL flag value.
If you have configured outlook then you might know it.


Anonymous said...

hi ankit

can you send the code for sending email in asp.net via proxy server.


Anonymous said...

check this out ..http://dotnetbeginner.spaces.live.com/blog/cns!C878CA0BAA85841F!157.entry


Unknown said...

I am trying to send email using Gmail using asp.net 3.5 in vwd 2008 express on vista. I am using the following code which is timing out when I debug.
===========================
MailMessage msgMail = new MailMessage("myemail@gmail.com", "myemail@gmail.com");
msgMail.Subject = "Test";
msgMail.Body = "This is a sample body";
SmtpClient s = new SmtpClient();
s.Host = "smtp.gmail.com";
s.Port = 465;
NetworkCredential basicAuthenticationInfo = new NetworkCredential("myemail@gmail.com", "mypassword");
s.UseDefaultCredentials = false;
s.Credentials = basicAuthenticationInfo;
s.EnableSsl = true;
s.Send(msgMail);
==============================
you can also email me at tgads004@gmail.com


gams said...

Hey thx ..... gr8 help.... after so much Googling :)


JAGADiSH V. said...

hi i m Jagadish here,, i m trying to mail sending through asp .net + C#,,, but i m getting the problem.... i m fresher in C#...

Can u ppl help to get this code.

the problem is that i want reply for FEEDBACK, at that time i know how to get the TO mail id and FROM mail id but i m facing problem in MAIL SENDING part.

Waiting for someone's reply for this.

- Jagadish V.


Anonymous said...

code for entering a name, id, and height using grid view in asp.net


efbolton said...

thxs 4 the article. solved my issue w/ little tweaking!!!!


Anonymous said...

thxs 4 the article!


.Net Developer said...

Interesting idea. I think the solution is good.


Anonymous said...

Hey,

This is a question for the webmaster/admin here at csharpdotnetfreak.blogspot.com.

Can I use some of the information from your blog post above if I provide a link back to your website?

Thanks,
Harry


Unknown said...

@harry: sure you can use :))


Anonymous said...

Hi - I am certainly happy to discover this. cool job!


Anonymous said...

I am delevoping windows application in c#..
In this m sending mails...
The code which i have written works fine at home...
but in college m not able to send mail due to proxy network....
my college's proxy address is 10.10.11.1 with port number 8080

please somebody help me.......


Anonymous said...

Hi - I am definitely happy to discover this. cool job!


Anonymous said...

Hey - I am really glad to find this. Good job!


Anonymous said...

Hey! Thank you for your blog! Honestly I have never come across anything that interesting.


Anonymous said...

Aloha there! Does anyone know where I can read additional posts on this topic?


Bincy said...

I want to know how to send mail with attachment. Can u plz help me???


Unknown said...

@Bincy: Please refer Send Email With Attachment In Asp.Net


Find More Articles