C# Sending Email

Here is a quick tip on sending email from a C# application. Sending email is quite simple; the example below was created in a Console Application.

Namespaces

These namespaces are both required.

Sponsored Links
using System.Net;
using System.Net.Mail;

C# Code

MailMessage mailMessage = new MailMessage();

string[] to = { "example@hotmail.co.uk" };
 
foreach (var m in to)
{
 mailMessage.To.Add(m);
}
 
mailMessage.Subject = "HELLO";
mailMessage.Body = "THIs IS A TEST";
mailMessage.From = new MailAddress("example@gmail.com", "displayname");
 
 
SmtpClient smtpMail = new SmtpClient();
smtpMail.Host = "smtp.gmail.com";
smtpMail.Credentials = new NetworkCredential("example@gmail.com", "YOURpassword");
smtpMail.EnableSsl = true;
 
 
try
{
 smtpMail.Send(mailMessage);
 Console.WriteLine("Message Sent");
}catch (Exception ex)
{
 Console.WriteLine(ex.Message.ToString());
}
 Console.ReadLine();

This example uses a Gmail smtp server and sends it to a Hotmail address.

Code Explained

Step 1

MailMessage mailMessage = new MailMessage();
 
string[] to = { "example@hotmail.co.uk" };
 
foreach (var m in to)
{
 mailMessage.To.Add(m);
}

mailMessage.Subject = "HELLO";
mailMessage.Body = "THIs IS A TEST";
mailMessage.From = new MailAddress("example@gmail.com", "displayname");

Here we first:

  • Create a new instance of the MailMessage Class
  • Create an array to store each email address
  • Loop through the array "to" and then to the collection of recipients using the mailMessage.To.Add method
  • Create the subject, body, and from. The subject and body require one parameter: mailMessage.In this case, from takes two parameters: the from address and display name.

Step 2

SmtpClient smtpMail = new SmtpClient();

smtpMail.Host = "smtp.gmail.com";
smtpMail.Credentials = new NetworkCredential("example@gmail.com", "YOURpassword");
smtpMail.EnableSsl = true;
 
try
{
smtpMail.Send(mailMessage);
Console.WriteLine("Message Sent");
}
catch (Exception ex)
{
 Console.WriteLine(ex.Message.ToString());
}
Console.ReadLine();

Here we send the message using the smtpClient class:

  • Create a new instance of the class
  • Specify the host (in this case, Google)
  • Provide the username and password
  • Set SSL to true (Google only likes secure connections)
  • Use a try catch block for any errors.

If you have any  problems, they are usually related to the port. The default port is 25, but you can change it by doing this:

smtpMail.Port = 123;