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


54 comments:

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

    ReplyDelete
  2. Thnxs

    It is working fine

    keep on :)

    ReplyDelete
  3. thanks for your code
    dlfree.net

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

    ReplyDelete
  5. Hi,

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

    What could be the problem?

    Emmao.

    ReplyDelete
  6. @:Emmao

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

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

    ReplyDelete
  8. @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

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

    ReplyDelete
  10. @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.");
    }

    }

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

    ReplyDelete
  12. @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

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

    ReplyDelete
  14. @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

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

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

    ReplyDelete
  17. @Miguel:

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

    ReplyDelete
  18. 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!!

    ReplyDelete
  19. @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 ?

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

    ReplyDelete
  21. @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

    ReplyDelete
  22. this works well with any smtp server but not with gmail

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

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

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

    ReplyDelete
  26. @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

    ReplyDelete
  27. This comment has been removed by a blog administrator.

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

    ReplyDelete
  29. @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")

    ReplyDelete
  30. kris of philippinesAugust 16, 2009 at 1:16 PM

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

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

    ReplyDelete
  32. @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

    ReplyDelete
  33. 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;
    }
    }
    }

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

    ReplyDelete
  35. hi ankit

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

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

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

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

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

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

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

    ReplyDelete
  42. thxs 4 the article!

    ReplyDelete
  43. Interesting idea. I think the solution is good.

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

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

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

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

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

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

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

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

    ReplyDelete