Saturday, June 6, 2009

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


www.tips-fb.com
Shout it
Stumble Upon Toolbar
Submit this story to DotNetKicks vote it on WebDevVote.com add to del.icio.us saved by 0 users
Subscribe to Feeds

36 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!


Adeeb said...

Thnxs

It is working fine

keep on :)


kashyap said...

hey tht was awesone


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


csharpdotnetfreak 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


amiT
amiT jaiN 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


amiT
amiT jaiN 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


amiT
amiT jaiN 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


amiT
amiT jaiN 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


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


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


amiT
amiT jaiN 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!!


amiT
amiT jaiN 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 :(


amiT
amiT jaiN 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


amiT
amiT jaiN 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 post has been removed by a blog administrator.


Atif 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


amiT
amiT jaiN 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")


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


amiT
amiT jaiN 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


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

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;
}
}
}


kris of philippines said...

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


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


About Me

My Photo
amiT jaiN
Hi, I am amiT jaiN Software engineer working on C#.NET and ASP.NET technologies
View my complete profile

Comments

.NET Resources

Find More Articles


Subscribe To Feeds

Subscribe by E-mail

Enter your email address:

Delivered by FeedBurner


Subscribe in your favorite reader

This site is best viewed with || You may get errors in proper display of this site if using Internet explorer


C#.NET Articles and tutorials,ASP.NET Articles - blog by amiT jaiN