Library: Send and email using GMail

thines01 0 Tallied Votes 715 Views Share

Here is a technique I use for sending an email using GMail.
Notice: You might need to change your email settings under Forwarding and POP/IMAP inside your GMail settings (to Enable POP).

Here is a test program for using the class library (shown in the snippet box):

using System;

namespace TestSendGmail
{
   using SendGmail;
   
   class Program
   {
      static void Main(string[] args)
      {
         string strError = "";

         if(!CSendGmail.SendMail(
            // credential from a secure source
            GetCred.CGetCred.GetCred("GMAIL"),
            "Test Subject", // subject
            "someone@somewhere.com", // To:
            "test message", // Body
            "", // Attachment
            ref strError // returned error message,if any
            ))
         {
            Console.WriteLine("Could not send mail: " + strError);
            return;
         }

         Console.WriteLine("Finished");
      }
   }
}
using System;
using System.Net;
using System.Net.Mail;

namespace SendGmail
{
   public class CSendGmail
   {
      public static bool SendMail(NetworkCredential cred, string strSubject, string strEmailTo, string strBody, string strFileAttach, ref string strError)
      {
         bool blnRetVal = true;
         try
         {
            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
            smtp.EnableSsl = true;
            //
            MailMessage msg = new MailMessage();
            if (!string.IsNullOrEmpty(strFileAttach))
            {
               msg.Attachments.Add(new Attachment(strFileAttach));
            }
            msg.To.Add(strEmailTo);
            msg.From = new MailAddress(cred.UserName);
            msg.Subject = strSubject;
            msg.IsBodyHtml = true;
            msg.Body = strBody;
            //msg->Priority = MailPriority::High;
            cred.Domain = "";
            smtp.Credentials = cred;
            smtp.Send(msg);
         }
         catch (Exception exc)
         {
            blnRetVal = false;
            strError = exc.Message;
         }

         return blnRetVal;
      }
   }
}