Thursday, June 30, 2016

Create a simple smtp email with html body

Smtp Email


Smtp Client


To create a smtp client, we need to specify a smtp host and port, port is an optional parameter.
for some Smtp clients, we need to provide credintials. we need a NetworkCredintial instance for that. We can use Secure Socket Layer (SSL) to encrypt the connection.












var client = new SmtpClient(host, Convert.ToInt32(port))
   {
      UseDefaultCredentials = true,
      Credentials = new NetworkCredential(username, password),
       EnableSsl = true
  };


This shows how to instantiate a smtp client, If you are using gmail, host is smtp.gmail.com or else some specific smtp server. If port is available, specify the port.

Mail Message

After working with Smtp client, then we need is MailMessage object.








    MailMessage message = new MailMessage();
    message.From = new MailAddress(fromAddress);
    foreach (string address in toAddress)
      message.To.Add(address);
    message.Subject = subject;
    message.Body = body;
    message.IsBodyHtml = true;

MailMessage from and to should be MailAddress instances.

In this example we used IsBodyHtml attribute, to notify mail body can be a html string.

Complete code is shown below























public static bool SendEmail(string host, int port, string username, string password, string fromAddress, List toAddress, string subject, string body) 


 bool emailSent = false; 

 MailMessage message = new MailMessage(); 
 message.From = new MailAddress(fromAddress); 

foreach (string address in toAddress) 
  message.To.Add(address); 
message.Subject = subject; 
message.Body = body; 
message.IsBodyHtml = true; 

var client = new SmtpClient(host, Convert.ToInt32(port)) 

  UseDefaultCredentials = true, 
  Credentials = new NetworkCredential(username, password), 
  EnableSsl = true 
}; 

try 

  client.Send(message); 
  emailSent = true; 
  logger.Info(string.Format("Email sent from {0} to {1}", fromAddress, 
               string.Join(",", toAddress))); 

catch (Exception ex) 

  emailSent = false; 
  logger.Error(ExceptionHandler.ToLongString(ex)); 


return emailSent; 

}

Downloads


TechNet Gallery


GitHub



No comments:

Post a Comment