Advertisement
drkbl

Authenticated SMTP C#

Jul 24th, 2018
333
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.04 KB | None | 0 0
  1. /* https://stackoverflow.com/questions/298363/how-can-i-make-smtp-authenticated-in-c-sharp */
  2.  
  3. using System.Net;
  4. using System.Net.Mail;
  5.  
  6. using(SmtpClient smtpClient = new SmtpClient())
  7. {
  8.     var basicCredential = new NetworkCredential("username", "password");
  9.     using(MailMessage message = new MailMessage())
  10.     {
  11.         MailAddress fromAddress = new MailAddress("from@yourdomain.com");
  12.  
  13.         smtpClient.Host = "mail.mydomain.com";
  14.         smtpClient.UseDefaultCredentials = false;
  15.         smtpClient.Credentials = basicCredential;
  16.  
  17.         message.From = fromAddress;
  18.         message.Subject = "your subject";
  19.         // Set IsBodyHtml to true means you can send HTML email.
  20.         message.IsBodyHtml = true;
  21.         message.Body = "<h1>your message body</h1>";
  22.         message.To.Add("to@anydomain.com");
  23.  
  24.         try
  25.         {
  26.             smtpClient.Send(message);
  27.         }
  28.         catch(Exception ex)
  29.         {
  30.             //Error, could not send the message
  31.             Response.Write(ex.Message);
  32.         }
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement