How can I make SMTP authenticated in C #

I am creating a new ASP.NET web application using SMTP to send a message. The problem is that smtp was not authenticated who sent the message.

How can I make SMTP authenticated in my program? Does C # have a class that has an attribute to enter a username and password?

+60
authentication c # smtp
Nov 18 '08 at 10:19
source share
5 answers
using System.Net; using System.Net.Mail; SmtpClient smtpClient = new SmtpClient(); NetworkCredential basicCredential = new NetworkCredential("username", "password"); MailMessage message = new MailMessage(); MailAddress fromAddress = new MailAddress("from@yourdomain.com"); smtpClient.Host = "mail.mydomain.com"; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = basicCredential; message.From = fromAddress; message.Subject = "your subject"; //Set IsBodyHtml to true means you can send HTML email. message.IsBodyHtml = true; message.Body = "<h1>your message body</h1>"; message.To.Add("to@anydomain.com"); try { smtpClient.Send(message); } catch(Exception ex) { //Error, could not send the message Response.Write(ex.Message); } 

You can use the code above.

+123
Nov 18 '08 at 10:29
source share

Make sure you set SmtpClient.Credentials after calling SmtpClient.UseDefaultCredentials = false .

The order is important since setting SmtpClient.UseDefaultCredentials = false will reset SmtpClient.Credentials to zero.

+59
Jan 12 '15 at 7:11
source share

Before sending a message, set the Credentials property.

+6
Nov 18 '08 at 10:32
source share

How do you send a message?

Classes in the System.Net.Mail namespace (which you should probably use) have full authentication support, either specified in Web.config or using the SmtpClient.Credentials property.

+1
Nov 18 '08 at 10:30
source share

To send a message via TLS / SSL, you need to set the Ssl of the SmtpClient class to true.

 string to = "jane@contoso.com"; string from = "ben@contoso.com"; MailMessage message = new MailMessage(from, to); message.Subject = "Using the new SMTP client."; message.Body = @"Using this new feature, you can send an e-mail message from an application very easily."; SmtpClient client = new SmtpClient(server); // Credentials are necessary if the server requires the client // to authenticate before it will send e-mail on the client behalf. client.UseDefaultCredentials = true; client.EnableSsl = true; client.Send(message); 
+1
Nov 01 '17 at 9:15 on
source share



All Articles