Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set username and password for SmtpClient object in .NET?

Tags:

c#

smtpclient

People also ask

Which property will be used for setting username and password for email server authentication?

If the UseDefaultCredentials property is set to false, then the value set in the Credentials property will be used for the credentials when connecting to the server.

What is SMTP client credentials?

Simple, the Credentials [^] property of the SmtpClient [^] object is used for authentication process on the SMTP server, it is your username/password used by the SMTP client, server or other application using which you can authenticate yourself to use the service.

What is SmtpClient C#?

Allows applications to send email by using the Simple Mail Transfer Protocol (SMTP). The SmtpClient type is obsolete on some platforms and not recommended on others; for more information, see the Remarks section.


The SmtpClient can be used by code:

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");

Use NetworkCredential

Yep, just add these two lines to your code.

var credentials = new System.Net.NetworkCredential("username", "password");

client.Credentials = credentials;

SmtpClient MyMail = new SmtpClient();
MailMessage MyMsg = new MailMessage();
MyMail.Host = "mail.eraygan.com";
MyMsg.Priority = MailPriority.High;
MyMsg.To.Add(new MailAddress(Mail));
MyMsg.Subject = Subject;
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.From = new MailAddress("username", "displayname");
MyMsg.BodyEncoding = Encoding.UTF8;
MyMsg.Body = Body;
MyMail.UseDefaultCredentials = false;
NetworkCredential MyCredentials = new NetworkCredential("username", "password");
MyMail.Credentials = MyCredentials;
MyMail.Send(MyMsg);