Using credentials with the .net SmtpClient class

I had a bit of trouble deciphering the MSDN article below:

What MSDN says about using credentials i.e the SmtpClient.Credentials property

Using a username and password with the new .net mailer is actually quite easy (C#):

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
mailer.Send("from@address.net", "to@address.net", "Subject line", "Main email text body");

As a sidenote, I was trying to send from an smtp server that was running on the same system as the site I was working on. That server uses the no-ip service to redirect the domain name to the dynamic IP the server sits at. The problem I ran into was that hotmail totally rejected the sent messages on receipt. I could send them ok but they just never came through on the other end, at the hotmail recipient. It took a lot of digging around for me to find out that it rejects mail sent from certain dynamic IP hosts such as no-ip. If you want to send it then you will have to use an smtp server that is NOT with one of these hosts.

Share Article

Comments: 8

Leave a reply

Please fill in the form fields and improve Skynet by completing the captcha!

Thank you! All comments are moderated so yours will appear shortly.
  • roland
    roland

    thanks, the MSDN article is not usefull, indeed.

  • StuBob
    StuBob

    Thank you for showing this example

  • Gordon Bell
    Gordon Bell

    If you want to send via the SMTP server using the credentials of the currently logged on user, you can replace:

    mailer.Credentials = new System.Net.NetworkCredential(“yourusername”, “yourpassword”);

    with simply:

    mailer.UseDefaultCredentials = true;

    Now, why would a property named .UseDefaultCredentials be false by default? 🙂

  • subtain Pervaiz
    subtain Pervaiz

    Thanks a lot. It works. But when i try to import user mail address and password directly from a text box, into the paramenters of System.Net.NetworkCredential, it doesnt work. What to do?

    mailer.Credentials = new System.Net.NetworkCredential(textboxUserName.Text, textboxPassword.Text);

  • Anonymous
    Anonymous

    I’d say the first thing to check is that you are using the correct username and password. Sounds like a dumb thing to suggest but it’s worth saying. Next I’d try outputting to screen the username and password that the system read from the text boxes. Make sure that no extra whitespace is getting added or prepended.

  • merca
    merca

    SmtpClient SmtpServer = new SmtpClient(“smtp.gmail.com”);
    SmtpServer.Port = 587;
    SmtpServer.Credentials =
    new System.Net.NetworkCredential(“username”, “password”);

    merca

  • Omer Farooq
    Omer Farooq

    Thanks, short and informative.

  • gailmarboo
    gailmarboo

If you keep on doing what you have always done then you will always be what you have always been.