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.
Comments: 8
thanks, the MSDN article is not usefull, indeed.
Thank you for showing this example
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? 🙂
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);
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.
SmtpClient SmtpServer = new SmtpClient(“smtp.gmail.com”);
SmtpServer.Port = 587;
SmtpServer.Credentials =
new System.Net.NetworkCredential(“username”, “password”);
merca
Thanks, short and informative.
SMTP Credential c# full source code
http://csharp.net-informations.com/communications/csharp-smtp-mail.htm
gail.