C#: Create a simple SMTP email with HTML body
SMTP Email
SMTP Client
To create an SMTP client, we need to specify an SMTP host and port, the port is an optional parameter.
For some SMTP clients, we need to provide credentials. We need a Network-credential 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 an SMTP client. If you are using Gmail, the host is smtp.gmail.com or else some specific SMTP server. If the port is available, specify the port.
Mail Message
After working with SMTP client, then we need is a 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 an HTML string.
Complete code is shown below
public static bool SendEmail(string host, int port, string username, string password, string fromAddress, List<string> 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
- You can download the source code from https://gallery.technet.microsoft.com/Create-a-simple-smtp-email-5a1656b1
GitHub
- You can also check the GitHub repo https://github.com/hansamaligamage/Scheduler