David Millington

Using credentials with the .net SmtpClient class


I had a bit of trouble decyphering 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 alot 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.

Leave a comment


gailmarboo says


SMTP Credential c# full source code

http://csharp.net-informations.com/communications/csharp-smtp-mail.htm

gail.

Omer Farooq says


Thanks, short and informative.

merca says


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

merca

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.

subtain Pervaiz says


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

Gordon Bell says


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? :)

StuBob says


Thank you for showing this example

roland says


thanks, the MSDN article is not usefull, indeed.
thought point page code people class install work player adapter system list panel directory via network problem adobe bit mode setup new time music update address site device version flash settings project xml box screen button control house file show simple option windows menu phone read think game pretty rocky