C# Sending an e-mail


This is something that may sound simple but looking around the internet you will find several solutions that … most of them are NOT working at all. For that reason, I decided to post the following solution which is working perfectly with Outlook and it is also tested with Gmail. (And of course, have a personal backup of this piece of code a.k.a snippet).

(Just for those who will try to use this snippet with GMail: The server may reject your actions for security reasons, make sure you set the correct settings in google mail)

using System;
using System.Net;
using System.Net.Mail;


public static bool Send(string to, string subject, string body, string filepath)
         MailMessage mM = new MailMessage();
         mM.From = new MailAddress(Base.Definitions.EMailAddress);
         mM.Subject = subject;
         if (!string.IsNullOrEmpty(filepath))
             mM.Attachments.Add(new Attachment(@"" + filepath));
         mM.Body = body;
         mM.IsBodyHtml = true;
         SmtpClient sC = new SmtpClient("smtp-mail.outlook.com");
         sC.Port = 587;
         sC.Credentials = new NetworkCredential(<mail address>, <password>);
         sC.EnableSsl = true;

         return true;
    catch (Exception)
        return false;
Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.