C# Sending an e-mail

C

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)
{
     try
     {
         MailMessage mM = new MailMessage();
         mM.From = new MailAddress(Base.Definitions.EMailAddress);
         mM.To.Add(to);
         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;

         sC.Send(mM);
         sC.Dispose();
         return true;
    }
    catch (Exception)
    {
        return false;
    }
}

 

Add comment

Categories

Tags