How to send email using c#


Back to learning
Created: 12/03/2011

How to send email using c#.

First what we need to do is include Mail namespace:

using System.Net.Mail;

and now we just need to add some code to our class:
we will make a function so we can use it later in our project
this funciton will recive  4 parameters: our message body, sender mail, reciver mail, and subject...
and return true or false (sended or error)


public static bool SendMail(string message, string mailFrom, string mailTo, string subject)
   {
    // If you whant to verify EMAIL string just use this:
    if (string.IsNullOrEmpty(message) || string.IsNullOrEmpty(mailFrom) || string.IsNullOrEmpty(mailTo)
    || string.IsNullOrEmpty(subject) || !Regex.IsMatch(mailFrom,
     @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
      @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
      RegexOptions.IgnoreCase))
         return false;

       //  Our mail
     MailMessage ourMessage= new MailMessage();
     ourMessage.To.Add(new MailAddress(mailTo));
      ourMessage.From = new MailAddress(mailFrom);
     ourMessage.Body = message;
    ourMessage.IsBodyHtml = true;
       ourMessage.Subject = subject;

       // 
SmtpClient (Class)
      //  Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).


       SmtpClient Client = new SmtpClient("smtp.live.com", 25);
       
Client.EnableSsl = true;
      
Client.Credentials = new System.Net.NetworkCredential("yourmail@hotmail.com", "yourpassword");

     try
     {
       
Client.Send(ourMessage);    // Try to send your mail.
         return true;                           // Mail sended
     }
     catch (Exception ex)
      {
          return false;                           // Send error
      }
    }


       
// using our function

        SendMail("mail body!","yourcompanyMail@hotmail.com","recivermail@hotmail.com","subject");